package com.blq.api.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.blq.api.domain.EvaluationBackup;
import com.blq.api.domain.MaterialAfter;
import com.blq.api.domain.MaterialBefore;
import com.blq.api.domain.Vo.SysUserVo;
import com.blq.api.mapper.AppMapper;
import com.blq.api.mapper.EvaluationBackupMapper;
import com.blq.api.mapper.MaterialAfterMapper;
import com.blq.api.mapper.MaterialBeforeMapper;
import com.blq.api.service.ApiService;
import com.blq.common.constant.Constants;
import com.blq.common.core.domain.R;
import com.blq.common.core.domain.entity.SysDept;
import com.blq.common.core.domain.entity.SysRole;
import com.blq.common.core.domain.entity.SysUser;
import com.blq.common.core.domain.model.XcxLoginUser;
import com.blq.common.enums.DeviceType;
import com.blq.common.exception.ServiceException;
import com.blq.common.helper.LoginHelper;
import com.blq.common.utils.*;
import com.blq.common.utils.redis.RedisUtils;
import com.blq.common.utils.wx.entity.Code2sessionResponse;
import com.blq.pay.WXConfig;
import com.blq.pay.service.IWxPayService;
import com.blq.system.domain.*;
import com.blq.system.mapper.*;
import com.blq.system.service.ISysConfigService;
import com.blq.system.service.ISysOssService;
import com.blq.system.service.SysLoginService;
import com.blq.system.service.SysPermissionService;
import com.blq.system.service.impl.SysUserServiceImpl;
import com.blq.utils.SendOrderMsg;
import com.blq.utils.WXPayConfig;
import com.blq.utils.WeixinUtil;
import com.blq.utils.WxConstants;
import com.blq.web.CustomerRepair.domain.CustomerRepair;
import com.blq.web.CustomerRepair.mapper.CustomerRepairMapper;
import com.blq.web.CustomerRepair.service.impl.CustomerRepairServiceImpl;
import com.blq.web.PayoutInformation.domain.MaterialInfo;
import com.blq.web.PayoutInformation.domain.PayoutInformation;
import com.blq.web.PayoutInformation.mapper.MaterialInfoMapper;
import com.blq.web.PayoutInformation.mapper.PayoutInformationMapper;
import com.blq.web.PayoutInformation.service.impl.PayoutInformationServiceImpl;
import com.blq.web.customerMode.entiy.*;
import com.blq.web.customerMode.mapper.*;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import jodd.util.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.blq.common.utils.DistanceUtils.getDistance;
import static com.blq.common.utils.DistanceUtils.getPoint;
import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;

/**
 * 服务实现
 *
 * @author: Blq <br>
 */
@Service
@Slf4j
public class ApiServiceImpl implements ApiService {

    private final SnowflakeIdWorker id = new SnowflakeIdWorker(0, 0);
    SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private AppMapper appMapper;
    @Autowired
    private EvaluationBackupMapper evaluationBackupMapper;
    @Autowired
    private MaterialAfterMapper materialAfterMapper;
    @Autowired
    private MaterialBeforeMapper materialBeforeMapper;
    @Autowired
    private SysNoticeMapper sysNoticeMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SysUserPostMapper sysUserPostMapper;
    @Autowired
    private SysUser sysUser;
    @Autowired
    private SysUserServiceImpl sysUserService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private PayoutInformationServiceImpl payoutInformationService;
    @Autowired
    private EvaluationMapper evaluationMapper;
    @Autowired
    private InvestigationMapper investigationMapper;
    @Autowired
    private MaterialInfoMapper materialInfoMapper;

    @Autowired
    private QuotationMapper quotationMapper;

    @Autowired
    private PayoutInformationMapper payoutInformationMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    //锁
    private static final ReentrantLock lock = new ReentrantLock();
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CustomerRepairMapper customerRepairMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysOperLogMapper sysOperLogMapper;
    @Autowired
    private CustomerRepairServiceImpl customerRepairServiceimpl;
    @Autowired
    private TicketMapper ticketMapper;

    @Autowired
    private ISysOssService iSysOssService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IWxPayService wxPayService;

    /**
     * 获取收款建源
     * @param orderId
     * @return
     */
    /*@Override
    public SysDept queryPayeeByOrder(String orderId) {
        CustomerRepair order = customerRepairMapper.selectById(orderId);
        String customerAddress = order.getCustomerAddress();
        for (SysDept sysDept : sysDeptMapper.selectListDept("1628618911551913985", "1")) {
            if (StringUtils.isNotBlank(sysDept.getCity()) && customerAddress.contains(sysDept.getCity().substring(0,2))){
                return sysDept;
            }
        }
        return sysDeptMapper.selectone("1628618911551913985");
    }*/

    /**
     * 获取收款服务商
     * @param orderId
     * @return
     */
    @Override
    public ResultMsg queryPayeeByOrder(String orderId) {
        String config = sysConfigService.selectConfigByKey("order.payee");
        if ("service".equals(config)) {
            CustomerRepair order = customerRepairMapper.selectById(orderId);
            if (StringUtils.isNotBlank(order.getCompanyId())) {
                SysDept dept = sysDeptMapper.selectone(order.getCompanyId());
                return ResultMsg.SELECT_SUCCESS.setNewData(dept);
            }
        } else if ("platform".equals(config)) {
            /*String payType = sysConfigService.selectConfigByKey("order.pay.type");
            if ("fast".equals(payType)) {
            } else {
            }*/
            return ResultMsg.SELECT_SUCCESS.setNewData(sysDeptMapper.selectById(100));
        }
        return ResultMsg.OBJECT_ERROR.setNewErrorMsg("获取收款方失败");
    }

    /**
     * 功能描述: 〈获取微信手机号〉 <br>
     *
     * @param jsonObject:
     * @return com.blq.common.utils.ResultMsg
     * @Author: Blq
     * @Date: 2022/7/14 10:55
     */
    @Override
    @SneakyThrows
    public ResultMsg wxPhone(JSONObject jsonObject) {
        if (jsonObject == null || StringUtils.isBlank(jsonObject.getString("code")) || StringUtils.isBlank(jsonObject.getString("iv")) || StringUtils.isBlank(jsonObject.getString("encryptedData"))) {
            return ResultMsg.ARGS_ERROR;
        } else {
            String encryptedData = jsonObject.getString("encryptedData");
            String iv = jsonObject.getString("iv");
            String code = jsonObject.getString("code");
            Code2sessionResponse code2sessionResponse = code2sessionForMini(code);
            if (code2sessionResponse == null) {
                return ResultMsg.OBJECT_ERROR.setNewErrorMsg("授权获取失败");
            } else {
                String s = encryptedData.replaceAll(" ", "+");
                String s1 = iv.replaceAll(" ", "+");
                String s2 = code2sessionResponse.getSessionKey().replaceAll(" ", "+");
                String res = WechatDecryptDataUtil.decryptData(s, s2, s1);
                Map<String, Object> parse = (Map<String, Object>) com.alibaba.fastjson.JSONObject.parse(res);
                if (parse != null) {
                    String phoneNumber = (String) parse.get("phoneNumber");
                    System.out.println("结果 = " + parse);
                    System.out.println("手机号码 = " + phoneNumber);
                    if (StringUtil.isBlank(phoneNumber)) {
                        return ResultMsg.OBJECT_ERROR.setNewErrorMsg("手机号为空");
                    }
                    return ResultMsg.OBJECT_SUCCESS.setNewData(parse);
                } else {
                    return ResultMsg.OBJECT_ERROR.setNewErrorMsg("授权信息为空");
                }
            }
        }
    }

    /**
     * 功能描述: 〈上传OSS配合二维码生成以及上传〉 <br>
     *
     * @param file:
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @Author: Blq
     * @Date: 2022/7/12 19:37
     */
    public ResultMsg sendOss(MultipartFile file, String notesName) {
        //文档上传接口
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("上传文件不能为空");
        }

        SysOss oss = iSysOssService.upload(file, notesName);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("notesName", oss.getNotesName());
        map.put("ossId", oss.getOssId().toString());
        return ResultMsg.UPLOAD_SUCCESS.setNewData(map);
    }

    /**
     * 根据code获取小程序session_key
     */
    public Code2sessionResponse code2sessionForMini(String code) {
        RestTemplate restTemplate1 = getRestTemplate();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={1}&secret={2}&js_code={3}&grant_type={4}";
        String jsonStr = restTemplate1.getForObject(url, String.class, WXPayConfig.APPID, WXPayConfig.SECRET, code, "authorization_code");
        return com.alibaba.fastjson.JSONObject.parseObject(jsonStr, Code2sessionResponse.class);
    }

    private RestTemplate getRestTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3000);
        requestFactory.setReadTimeout(3000);
        RestTemplate restTemplate1 = new RestTemplate(requestFactory);
        return restTemplate1;
    }

    /**
     * @Description: 发送手机验证码
     * @Author: Blq <br>
     * @Date: 2022/8/26 0026 13:44
     * @Param: jsonObject
     * @Return: com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg senndMessage(JSONObject jsonObject) {
        // 注册验证码
        if ("1".equals(jsonObject.getString("status"))) {
            String message = "您的验证码为${code} 请不要将验证码告诉他人，您正在注册易能。";
            log.info(message);
            SendMessageUtils.sendDIY(message, jsonObject.getString("phone"));
            return ResultMsg.OBJECT_SUCCESS;
        }
        // 修改手机号验证码
        if ("2".equals(jsonObject.getString("status"))) {
            String message = "您的验证码为${code} 请不要将验证码告诉他人。";
            log.info(message);
            SendMessageUtils.sendDIY(message, jsonObject.getString("phone"));
            return ResultMsg.OBJECT_SUCCESS;
        }
        return ResultMsg.ARGS_ERROR;
    }

    /**
     * APP绑定微信账户
     * @return
     */
    @Override
    public ResultMsg wxAppAuth(JSONObject json) {
        System.out.println(json);
        // xcxCode 为 小程序调用 wx.login 授权后获取
        // todo 以下自行实现
        // 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.WX_APP_APP_ID);
        param.put("secret", Constants.WX_APP_APP_SECRET);
        param.put("code", json.getString("code"));
        param.put("grant_type", Constants.WX_LOGIN_GRANT_TYPE);
//        param.put("scope", "snsapi_userinfo");
        // 发送请求
        String wxResult = HttpClientUtil.doGet(Constants.WX_APP_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 获取参数返回的
//        String session_key = jsonObject.getString("session_key");
        //返回微信小程序openId
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(openid)) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("微信授权失败");
        }
        Map<String, String> param2 = new HashMap<>();
        param2.put("access_token", jsonObject.getString("access_token"));
        param2.put("openid", openid);
        // 获取用户信息
        String wxUser = HttpClientUtil.doGet(Constants.WX_APP_USERINFO, param2);
        JSONObject wxUserInfo = JSONObject.parseObject(wxUser);
        String nickname = wxUserInfo.getString("nickname");
        if (StringUtils.isBlank(nickname)) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("获取微信头像昵称失败");
        }
        String wxAvatar = wxUserInfo.getString("headimgurl");
        String userId = json.getString("userId");
        if (StringUtils.isNotBlank(userId)) {
            SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("openid", openid));
            if (user != null && !userId.equals(user.getUserId().toString())) {
                String nc = user.getPhonenumber().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2");
                return ResultMsg.OBJECT_ERROR.setNewErrorMsg("此微信已绑定到" + nc + "账号");
            }
            SysUser sysUser = sysUserMapper.selectById(userId);
            if (sysUser != null) {
                sysUser.setOpenid(openid);
                sysUser.setWxName(nickname);
                sysUser.setWxAvatar(wxAvatar);
                sysUserMapper.updateById(sysUser);
            }
        }
        JSONObject info = new JSONObject();
        info.put("openid", openid);
        info.put("wxName", nickname);
        info.put("wxAvatar", wxAvatar);
        return ResultMsg.OBJECT_SUCCESS.setNewData(info);
    }

    /**
     * 微信授权
     * @return
     */
    @Override
    public ResultMsg xcxAuth(JSONObject json) {
        System.out.println(json);
        // xcxCode 为 小程序调用 wx.login 授权后获取
        // todo 以下自行实现
        // 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.WX_APP_ID);
        param.put("secret", Constants.WX_APP_SECRET);
        param.put("js_code", json.getString("code"));
        param.put("grant_type", Constants.WX_LOGIN_GRANT_TYPE);
//        param.put("scope", "snsapi_userinfo");
        // 发送请求
        String wxResult = HttpClientUtil.doGet(Constants.WX_XCX_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 获取参数返回的
//        String session_key = jsonObject.getString("session_key");
        //返回微信小程序openId
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(openid)) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("微信授权失败");
        }
        JSONObject info = new JSONObject();
        info.put("openid", openid);
        return ResultMsg.OBJECT_SUCCESS.setNewData(info);
    }

    /**
     * 小程序注册及登录
     * @return
     */
    @Override
    public ResultMsg xcxLogin(JSONObject json) {
        System.out.println(json);
        // xcxCode 为 小程序调用 wx.login 授权后获取
        // todo 以下自行实现
        // 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        // 配置请求参数
        Map<String, String> param = new HashMap<>();
        param.put("appid", Constants.WX_APP_ID);
        param.put("secret", Constants.WX_APP_SECRET);
        param.put("js_code", json.getString("code"));
        param.put("grant_type", Constants.WX_LOGIN_GRANT_TYPE);
//        param.put("scope", "snsapi_userinfo");
        // 发送请求
        String wxResult = HttpClientUtil.doGet(Constants.WX_XCX_LOGIN_URL, param);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        // 获取参数返回的
        String session_key = jsonObject.getString("session_key");
        //返回微信小程序openId
        String openid = jsonObject.getString("openid");
        if (StringUtils.isBlank(openid)) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("授权登录失败");
        }
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("openid", openid));
        if (sysUser != null) {
            JSONObject info = appMapper.getUserInfoByUserName(sysUser.getUserName());
            String token = sysLoginService.appLogin(sysUser.getUserName());
            if (ObjectUtil.isNotNull(info)) {
                info.put("token", token);
            }
            return ResultMsg.OBJECT_SUCCESS.setNewData(info);
        }
        JSONObject info = new JSONObject();
        info.put("getPhone", true);
        info.put("session_key", session_key);
        info.put("openid", openid);
        return ResultMsg.OBJECT_SUCCESS.setNewData(info);
    }

    /**
     * 微信授权获取手机注册并登录
     * @param json
     * @return
     */
    @Override
    public ResultMsg xcxRegister(JSONObject json) {
        JSONObject decryptData = WeixinUtil.decryptData(json.getString("encryptedData"), json.getString("session_key"), json.getString("iv"));
        if (decryptData == null) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("授权信息获取失败");
        }
        System.out.println(decryptData);
        if (decryptData.get("phoneNumber") == null) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("授权信息获取手机号失败");
        }
        String phoneNumber = decryptData.getString("phoneNumber");
//            UserInfo user_name = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_name", phoneNumber));
        sysUser = sysUserMapper.selectUserByUserName(phoneNumber);
        //JSONObject info = appMapper.getUserInfoByUserName(phoneNumber);
        if (sysUser != null) {
            if (StringUtils.isNotBlank(sysUser.getOpenid())) {
                return ResultMsg.OBJECT_ERROR.setNewErrorMsg("当前手机号已绑定别的微信，可直接使用手机号登录");
            }
            sysUser.setOpenid(json.getString("openid"));
            sysUserMapper.updateById(sysUser);
            JSONObject info = appMapper.getUserInfoByUserName(sysUser.getUserName());
            String token = sysLoginService.appLogin(sysUser.getUserName());
            if (ObjectUtil.isNotNull(info)) {
                info.put("token", token);
            }
            return ResultMsg.OBJECT_SUCCESS.setNewData(info);
        }
//            JSONObject rawData = json.getJSONObject("rawData");
        String avatarUrl = "http://xinxifa.oss-accelerate.aliyuncs.com/2022/08/26/e30e98e7f4d647c4b5f27721b1764dd5.jpg";
//            if (rawData != null) {
//                avatarUrl = rawData.getString("avatarUrl");
//            }
        String nickName = phoneNumber.substring(phoneNumber.length() - 4) + "客户";
//            String nickName = phoneNumber.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2");
        sysUser = new SysUser();
        sysUser.setUserName(phoneNumber);
        sysUser.setNickName(nickName);
        sysUser.setPhonenumber(phoneNumber);
        sysUser.setAvatar(avatarUrl);
        sysUser.setDelFlag("0");
//            sysUser.setPassword(userPassword2);
        sysUser.setCreateBy("xcx");
//            sysUser.setEmail("未设置");
        sysUser.setFlag("0");//
        sysUser.setDeptId(1613808083627782145L);
        Date date = new Date();
        sysUser.setCreateTime(date);
        sysUser.setStatus("0");
        sysUser.setOpenid(json.getString("openid"));
        sysUserMapper.insert(sysUser);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(phoneNumber);
//            userInfo.setUserPassword(userPassword2);
        userInfo.setUserImage(avatarUrl);
//            userInfo.setUserAddress(userAddress);
        userInfo.setUserId(String.valueOf(sysUser.getUserId()));
        userInfo.setCreateBy("xcx");
        userInfo.setCreateTime(date);
        userInfo.setUserNickName(nickName);
        userInfo.setUserFlag("0");
//            userInfo.setProvince(province);
//            userInfo.setCity(city);
//            userInfo.setArea(area);
//            userInfo.setLongitude(lng);
//            userInfo.setLatitude(lat);
        userInfoMapper.insert(userInfo);
        JSONObject info = appMapper.getUserInfoByUserName(phoneNumber);
        String token = sysLoginService.appLogin(phoneNumber);
        if (ObjectUtil.isNotNull(info)) {
            info.put("token", token);
        }
        return ResultMsg.OBJECT_SUCCESS.setNewData(info);
    }

    /**
     * @Description: 用户注册
     * @Author: Blq <br>
     * @Date: 2022/8/26 0026 11:26
     * @Param: jsonObject
     * @Return: com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg addUser(JSONObject jsonObject) {
        //用户名字
        String code = RedisUtils.getCacheObject(jsonObject.getString("userName"));
        if (StringUtils.isEmpty(code)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("验证码不能为空");
        String userPassword = jsonObject.getString("userPassword");
        if (StringUtils.isEmpty(userPassword)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("密码不能为空");
        String userAddress = jsonObject.getString("userAddress");
//        if (StringUtils.isEmpty(userAddress)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("地址不能为空");
        String phone = jsonObject.getString("userName");
        if (StringUtils.isEmpty(phone)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户名不能为空");
        String province = jsonObject.getString("province");//省
        String city = jsonObject.getString("city");//州市
        String area = jsonObject.getString("area");//区县
        String lng = jsonObject.getString("lng");//纬度
        String lat = jsonObject.getString("lat");//经度

        /*String faceScore = Md5Utils.md5enc("1");
        String userPassword1 = faceScore + userPassword;
        String userPassword2 = Md5Utils.md5enc(userPassword1);*/

        String userPassword2 = BCrypt.hashpw(userPassword);

        //幂等
        UserInfo user_name = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_name", phone));
        if (user_name == null) {
            if (code.equals(jsonObject.getString("code"))) {
                SysUser sysUser1 = new SysUser();
                sysUser1.setUserName(phone);
                sysUser1.setNickName("未设置");
                sysUser1.setPhonenumber(phone);
//                long userID = id.nextId();//用户id
//                sysUser1.setUserId(userID);
                sysUser1.setAvatar("http://xinxifa.oss-accelerate.aliyuncs.com/2022/08/26/e30e98e7f4d647c4b5f27721b1764dd5.jpg");
                sysUser1.setDelFlag("0");
                sysUser1.setPassword(userPassword2);
                sysUser1.setCreateBy("App");
//                sysUser1.setEmail("未设置");
                sysUser1.setFlag("0");//
                sysUser1.setDeptId(1613808083627782145L);
                Date date = new Date();
                sysUser1.setCreateTime(date);
                sysUser1.setStatus("0");
                sysUserMapper.insert(sysUser1);

                UserInfo userInfo = new UserInfo();
                userInfo.setUserName(phone);
                userInfo.setUserPassword(userPassword2);
                userInfo.setUserImage("http://xinxifa.oss-accelerate.aliyuncs.com/2022/08/26/e30e98e7f4d647c4b5f27721b1764dd5.jpg");
                userInfo.setUserAddress(userAddress);
                userInfo.setUserId(String.valueOf(sysUser1.getUserId()));
                userInfo.setCreateBy("App");
                userInfo.setCreateTime(date);
                userInfo.setUserNickName("未设置");
                userInfo.setUserFlag("0");
                userInfo.setProvince(province);
                userInfo.setCity(city);
                userInfo.setArea(area);
                userInfo.setLongitude(lng);
                userInfo.setLatitude(lat);
                userInfoMapper.insert(userInfo);
                return ResultMsg.INSERT_SUCCESS.setNewErrorMsg("注册成功 !");
            }
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("验证码已过期,请重新获取验证码");
        } else {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("该手机号已经注册过了");
        }
    }

    /**
     * @Description: 用户登录
     * @Author: Blq <br>
     * @Date: 2022/8/26 0026 13:37
     * @Param: jsonObject
     * @Return: com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg userLogin(JSONObject jsonObject) {
        JSONObject info = appMapper.getUserInfoByUserName(jsonObject.getString("userName"));
        //密码
        String password = jsonObject.getString("userPassword");
        //密码加密
        //根据用户手机号加盐
        String faceScore = Md5Utils.md5enc("1");
        String userPassword1 = faceScore + password;
        String userPassword = Md5Utils.md5enc(userPassword1);

        if (info == null) return ResultMsg.SELECT_ERROR.setNewErrorMsg("查无此信息,请注册");
        if (info.getString("userPassword").equals(userPassword)) {
            return ResultMsg.LOGIN_SUCCESS.setNewData(info);
        } else {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("密码错误");
        }
    }

    /**
     * @Description: 新增订单
     * @Author: Blq <br>
     * @Date: 2022/8/30 0030 8:55
     * @Param: jsonObject
     * @Return: com.blq.common.utils.ResultMsg
     **/
    @Transactional
    @Override
    public ResultMsg addCustomerRepair(JSONObject jsonObject) {

        //取值--判断
        String useraddress = jsonObject.getString("customerAddress");
        String usercity = jsonObject.getString("customerCity");
        String customerFiles = jsonObject.getString("customerFiles");//非必填
        String Help = jsonObject.getString("customerHelp");
        String userid = jsonObject.getString("customerId");//----1023995635902185472
        String customerMessage = jsonObject.getString("customerMessage");//----1023995635902185472
        String userName = jsonObject.getString("customerName");
        String userPhone = jsonObject.getString("customerPhone");
        String customerTimer = jsonObject.getString("customerTimer");
        String Auto = jsonObject.getString("customerAuto");
        String customerUnit = jsonObject.getString("customerUnit");

        String liaison = jsonObject.getString("liaison");
        String liaisonPhone = jsonObject.getString("liaisonPhone");

        String province = jsonObject.getString("province");//省
        String city = jsonObject.getString("city");//州市
        String area = jsonObject.getString("area");//区县
        String lng = jsonObject.getString("lng");//纬度
        String lat = jsonObject.getString("lat");//经度

        if (StringUtils.isBlank(Help)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("业务类型不能为空");
        if (StringUtils.isBlank(userid)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("当前登录人不能为空");
        if (StringUtils.isBlank(useraddress)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户地址不能为空");//地址
        if (StringUtils.isBlank(Auto)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("手动自动不能为空");//自动分配手动分配
        if (StringUtils.isBlank(usercity)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("城市不能为空");//城市
        if (StringUtils.isBlank(userName)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户名字不能为空");
        if (StringUtils.isBlank(userPhone)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户手机号不能为空");
        if (StringUtils.isBlank(customerTimer)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("预约时间不能为空");
        if (StringUtils.isBlank(lng) && StringUtils.isBlank(lat)) {
            return ResultMsg.ARGS_ERROR.setNewErrorMsg("经纬度不能为空");
        }
        if (StringUtils.isBlank(liaison)) {
            liaison = userName;
        }
        if (StringUtils.isBlank(liaisonPhone)) {
            liaisonPhone = userPhone;
        }
        //数据准备
        String message = null;//返回的信息
        String master = null;
        int i;
        Date date = new Date();

        long orderId = id.nextId();//工单id
        //业务
        //把对应的工单数据放入对象中-准备添加
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(String.valueOf(orderId));
        customerRepair.setCreateBy(userid);
        customerRepair.setCustomerAddress(useraddress);
        customerRepair.setCustomerCity(usercity);
        customerRepair.setCustomerFiles(customerFiles);
        customerRepair.setCustomerHelp(Help);
        customerRepair.setCustomerId(userid);
        customerRepair.setCustomerMessage(customerMessage);
        customerRepair.setCustomerName(userName);
        customerRepair.setCustomerPhone(userPhone);
        customerRepair.setLiaison(liaison);
        customerRepair.setLiaisonPhone(liaisonPhone);
        customerRepair.setCustomerTimer(customerTimer);
        customerRepair.setSearchable("0");//默认供电所不可查
        customerRepair.setCreateTime(date);
        customerRepair.setUpdateTime(date);
        customerRepair.setCustomerAuto(Auto);
        customerRepair.setProvince(province);
        customerRepair.setCity(city);
        customerRepair.setArea(area);
        customerRepair.setLon(lng);
        customerRepair.setLat(lat);

        SysUser smsUser = null;
        if (jsonObject.getString("customerAuto").equals("2")) {//自定义指派
            //判断
            String workerman = jsonObject.getString("customerPlayer");
            if (StringUtils.isBlank(workerman)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("自定义指派的人员不能为空");

            //获取公司id
            Long companyid = getOrgId(workerman.split(",")[0]);
            customerRepair.setCompanyId(String.valueOf(companyid));//公司 id
            customerRepair.setCustomerFlag("0");//工单状态---待接单
            customerRepair.setReceiverBy(workerman);//指定以指派放入员工
            customerRepair.setReceiverMan(workerman);
//            customerRepair.setReceiveTime(new Date());
            customerRepair.setUpdateTime(new Date());
            appMapper.addCustomerRepair(customerRepair);//新增(创建人,创建时间,工单id,更新时间,接单人,公司id)
            smsUser = sysUserMapper.selectById(workerman);

            //审核信息添加前幂等
            /*List<Ticket> ticket_repair = ticketMapper.selectList(new QueryWrapper<Ticket>().eq("ticket_repair", String.valueOf(orderId)));
            if (ticket_repair.size() > 0) return ResultMsg.ARGS_ERROR.setNewErrorMsg("审核信息已存在,不能重复提交");

            //添加审核订单--先把工人放进去---(创建时间先不添加: 待提交审核的时候添加)
            Ticket ticket = new Ticket();
            ticket.setTicketRepair(String.valueOf(orderId));//工单id
            ticket.setTicketUser(workerman);
            ticket.setCreateBy(userid);
            ticket.setCreateTime(date);
            ticketMapper.insert(ticket);//添加(工单id,工人,当前人)*/

        } else {//自动指派
            //分配规则
            /*SysUser worker = allocationNew(lng, lat, customerUnit, city);
//            String allocation = Allocation(lng, lat);

            if (worker != null) {
                customerRepair.setReceiverBy(worker.getUserId().toString());//指定以指派放入员工
                customerRepair.setCustomerFlag("0");
                customerRepair.setUpdateTime(new Date());
                customerRepair.setCompanyId(String.valueOf(worker.getDeptId()));//公司id
                customerRepair.setReceiverMan(worker.getUserId().toString());
                message = "您的" + Help + ",分配给<" + worker.getNickName() + ">师傅,师傅会在15分钟内接单!";
                smsUser = worker;
            } else {//放进工单池
                customerRepair.setCustomerFlag("99");//状态
                customerRepair.setReceiverBy(null);//接单人
                message = "正在为您寻找空闲的师傅,暂时把您的订单移交到订单池,请您耐心等待 !";
            }*/
            // 直接放工单池，5分钟后无人接单再自动分配
            customerRepair.setCompanyId(customerUnit);
            customerRepair.setCustomerFlag("99");//状态
            customerRepair.setReceiverBy(null);//接单人
            message = "您的订单已移交到订单池，等待空闲的师傅接单，请您耐心等待 !";
            appMapper.addCustomerRepair(customerRepair);
            // 短信提醒
            poolSendWorker(customerRepair);
        }
        //生成公告信息
        SysNotice sysNotice = new SysNotice();
        sysNotice.setNoticeTitle("订单更新状态");//公告标题
        sysNotice.setNoticeType("1");//公告类型
        sysNotice.setNoticeContent("尊敬的" + getUserName(userid) + "用户:您好," + message);//公告类容
        sysNotice.setStatus("0");//公告状态
        sysNotice.setCreateBy(userid);//创建人
        sysNotice.setCreateTime(date);//创建时间
        sysNotice.setRemark("订单创建");
        sysNotice.setReadNo("0");//用户未读状态
        sysNotice.setReadNoWorker("0");//工人未读状态
        sysNotice.setCustomerKey(String.valueOf(orderId));//工单号
        sysNoticeMapper.insert(sysNotice);
        //短信提醒
        if (smsUser != null) {
            SendOrderMsg.sendDIY("新单来啦！提醒：您有一份<" + Help + ">订单待接单，请尽快处理。", smsUser.getPhonenumber());
        }
        return ResultMsg.OBJECT_SUCCESS.setNewErrorMsg("创建工单成功");
    }

    /**
     * 短信提醒该区域各服务商默认接单人有新单子
     * @param order
     */
    public void poolSendWorker(CustomerRepair order) {
        // 短信提醒该区域各服务商默认接单人有新单子
        List<SysDept> sysDepts = sysDeptMapper.selectList(new QueryWrapper<SysDept>().eq("type_id", 3)
                .eq("del_flag", 0).eq("dept_type", 1)
                .eq("city", order.getCity()).eq("area", order.getArea()));
        for (SysDept dept : sysDepts) {
            if (dept.getReceiver() == 1) {
                List<SysUser> users = sysUserMapper.selectWorkerByDept(dept.getDeptId().toString(), "worker");
                for (SysUser user : users) {
                    if (user.getReceiver() == 1) {
                        SendOrderMsg.sendDIY("新单来啦！提醒：订单池有一份<" + order.getCustomerHelp() + ">新订单进来了，速速抢单。", user.getPhonenumber());
                    }
                }
            }
        }
    }

    @Override
    public void automaticDispatch(String orderId) {
        CustomerRepair customerRepair = customerRepairMapper.selectById(orderId);
        if (customerRepair != null) {
            SysUser worker = allocationNew(customerRepair.getLon(), customerRepair.getLat(), customerRepair.getCompanyId(), customerRepair.getCity(), customerRepair.getArea());
//            String allocation = Allocation(lng, lat);
            if (worker != null) {
                customerRepair.setReceiverBy(worker.getUserId().toString());//指定以指派放入员工
                customerRepair.setCustomerFlag("0");
//                customerRepair.setReceiveTime(new Date());
                customerRepair.setCompanyId(String.valueOf(worker.getDeptId()));//公司id
                customerRepair.setReceiverMan(worker.getUserId().toString());
                customerRepair.setUpdateTime(new Date());
                customerRepairMapper.updateById(customerRepair);
//                customerRepairMapper.updateCustomerRepairBykey(customerRepair);
                String message = "尊敬的用户您好，您的" + customerRepair.getCustomerHelp() + ",分配给<" + worker.getNickName() + ">师傅,师傅会在15分钟内接单!";
                SendOrderMsg.sendDIY("新单来啦！提醒：您有一份<" + customerRepair.getCustomerHelp() + ">订单待接单，请尽快处理。", worker.getPhonenumber());
                if (StringUtils.isNotBlank(customerRepair.getCustomerPhone())) {
                    SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + customerRepair.getCustomerHelp() + ">订单被指派给了<" + worker.getNickName() + ">[" + worker.getPhonenumber() + "]师傅接单，接下来由他完成您的订单。", customerRepair.getCustomerPhone(), customerRepair.getLiaisonPhone());
                }
                customerRepairServiceimpl.updateNotice(null, orderId, "备注", message, "0", null, null, null);
            } else {
                customerRepair.setUpdateTime(new Date());
                customerRepairMapper.updateById(customerRepair);
            }
        }
    }

    @Override
    public void automaticDispatch() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    List<CustomerRepair> customerRepairs = customerRepairMapper.selectTimeoutOrderPool(10);
                    if (customerRepairs.size() > 0) {
                        for (CustomerRepair customerRepair : customerRepairs) {
                            automaticDispatch(customerRepair.getCustomerKey());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    TimeUnit.SECONDS.sleep(60);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.setName("工单池超时处理");
        thread.start();
    }

    /**
     * @Author: xiaw
     * 根据员工id获取公司id
     */
    public Long getOrgId(String workerman) {
        SysUser sysUser = sysUserMapper.selectById(workerman);
        if (sysUser != null && sysUser.getDeptId() != null) {
            if (sysUser.getDeptId() == 1613808083627782145L) {
                return sysUser.getDeptId();
            }
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            if (sysDept != null) {
                if (sysDept.getDeptType() == 1) {
                    return sysUser.getDeptId();
                }
                String[] split = sysDept.getAncestors().split(",");
                for (int i = split.length - 1; i > 1; i--) {
                    SysDept dept = sysDeptMapper.selectById(split[i]);
                    if (dept.getDeptType() == 1) {
                        return dept.getDeptId();
                    }
                }
            }
        }
        throw new ServiceException("获取人员公司信息失败");
//        return null;
        /*QueryWrapper<SysUser> select = new QueryWrapper<SysUser>()
                .eq("user_id", workerman).select("dept_id");
        Long deptId = sysUserMapper.selectOne(select).getDeptId();
        //根据部门id查次顶级部门
        String dept_id = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", String.valueOf(deptId))).getAncestors();
        String[] split1 = dept_id.split(",");
        if (split1.length > 2) {
            return new Long(split1[2]);
        } else {
            return deptId;
        }*/
    }

    public SysUser allocationNew(String lng, String lat, String customerUnit, String city, String area) {
        Point point = new Point(new Double(lng), new Double(lat));
        List<SysDept> sysDepts = sysDeptMapper.selectServiceList(customerUnit, city, area);
        SysDept _dept = null;
        double d = -1;
        if (sysDepts.size() > 0) {
            // 先分配到配置了默认接单的单位
            for (SysDept sysDept : sysDepts) {
                if (sysDept.getReceiver() == 1) {
                    SysUser sysUser = queryWorkerByDept(sysDept);
                    if (sysUser != null) {
                        return sysUser;
                    }
                }
            }
            // 分配距离最近的服务商
            /*for (SysDept sysDept : sysDepts) {
                if (StringUtils.isNotBlank(sysDept.getLon()) && StringUtils.isNotBlank(sysDept.getLat())) {
                    Point pointDept = new Point(new Double(sysDept.getLon()), new Double(sysDept.getLat()));
                    double distance = getDistance(point, pointDept);
                    if (d != -1) {
                        if (distance < d) {
                            _dept = sysDept;
                            d = distance;
                        }
                    } else {
                        d = distance;
                        _dept = sysDept;
                    }
                }else {
                    _dept = (_dept == null ? sysDept : _dept);
                }
            }*/
        }
        return null;
//        return queryWorkerByDept(_dept);
    }

    public SysUser queryWorkerByDept(SysDept _dept) {
        if (_dept != null) {
            List<SysUser> users = sysUserMapper.selectWorkerByDept(_dept.getDeptId().toString(), "worker");
            for (SysUser user : users) {
                if (user.getReceiver() == 1) {
                    user.setDeptId(getOrgId(user.getUserId().toString()));
                    return user;
                }
            }
            /*if (users.size() > 0) {
                int i = (int) (Math.random() * users.size());
                SysUser worker = users.get(i);
                worker.setDeptId(getOrgId(worker.getUserId().toString()));
                return worker;
            }*/
        }
        return null;
    }

    /**
     * @Author: xiaw
     * 首先根据区域查找该区域的所有公司
     *  然后根据经纬度分配到最近的公司
     *      如果该公司有自动接单人--分配给自动接单人
     *      如果没有,展示给该公司所有人员
     */
    public String Allocation(String lng, String lat) {
        Point point = new Point(new Double(lng), new Double(lat));
        //查到所有的师傅.随机分配
        String role = "分公司施工人员";    //@ 维修师傅
        //角色id
        Long roleId = sysRoleMapper.selectOne(new QueryWrapper<SysRole>().eq("role_name", role)).getRoleId();
        //查到该城市的师傅集合
        List<SysUserRole> role_id = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("role_id", roleId));
        List<UserInfo> list = new ArrayList<>();
        for (SysUserRole sysUserRole : role_id) {
            //加上地址区域限制
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("user_id", sysUserRole.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
            if (userInfo != null) list.add(userInfo);
        }
        int size1 = 0;
        UserInfo nearestUserInfo = null;
        while (size1 < list.size()) {
            nearestUserInfo = getNearestUserInfo(point, list);
            if (selelctPending(nearestUserInfo.getUserId()).size() < 2) {
                nearestUserInfo = nearestUserInfo;
                break;
            }
            list.remove(nearestUserInfo);
            if (size1 == list.size()) break;
        }
        return nearestUserInfo.getUserId();
    }

    /**
     * @Author: xiaw
     * 根据工单修改任何数据
     */
    public void updateCustomerRepairBykey(CustomerRepair customerRepair) {
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);
    }

    /**
     * @Author: xiaw
     * 根据师傅id获取师傅名字
     */
    public String getUserName(String aLong1) {
        return sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", aLong1)).getNickName();
    }


    /**
     * @param point     用户指定的地址坐标
     * @param userInfos 商店
     * @return
     */
    public static UserInfo getNearestUserInfo(Point point, List<UserInfo> userInfos) {

        //如果传过来的集合只有一家店铺,那么直接将这家店铺的信息返回就是最近的店铺了
        UserInfo userInfo = userInfos.get(0);
        double distance = getDistance(point, getPoint(userInfo.getUserAddress()));
        double minDistance = distance;
        if (userInfos.size() > 1) {
            for (int i = 1; i < userInfos.size(); i++) {
                Point point1 = getPoint(userInfos.get(i).getUserAddress());
                double distanceTmp = getDistance(point, point1);
                if (distanceTmp < distance) {
                    userInfo = userInfos.get(i);
                    minDistance = distanceTmp;
                }
            }
        }

//        if (minDistance>50000){ //大于50公里，没有合适的店铺
//            return null;
//        }
        return userInfo;
    }



    /**
     * @Description 获取我发布的订单
     * @Author Blq <Br />
     * @Date 8:36 2022/9/1
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg getMyCustomerRepair(JSONObject jsonObject) {
        String userId1 = jsonObject.getString("userId");
        if (StringUtils.isBlank(userId1)) return ResultMsg.ARGS_ERROR;
        String status1 = jsonObject.getString("status");
        if (StringUtils.isBlank(status1)) return ResultMsg.ARGS_ERROR;
        QueryWrapper<CustomerRepair> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_id", userId1);
        wrapper.eq("customer_flag", status1);
        List<CustomerRepair> list = customerRepairMapper.selectList(wrapper);
        return ResultMsg.SELECT_SUCCESS.setNewData(list);
    }

    /**
     * @Description 根据用户id获取用户信息
     * @Author Blq <Br />
     * @Date 8:44 2022/9/5
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg getUserInfoById(JSONObject jsonObject) {
//        SysUserVo sysUserVo = new SysUserVo();
        String userId = jsonObject.getString("userId");

        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser == null) return ResultMsg.ARGS_ERROR.setNewErrorMsg("请登录");
        SysUserVo sysUserVo = BeanUtil.toBean(sysUser, SysUserVo.class);
//        sysUserVo.setUserId(sysUser.getUserId());
//        sysUserVo.setNickName(sysUser.getNickName());
//        sysUserVo.setPhonenumber(sysUser.getPhonenumber());
        //判断当前登录用户是不是客户
        Long deptId = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", userId)).getDeptId();
        if (deptId != 1613808083627782145L) {//不是客户
            // 岗位
            String posts = sysUserService.selectUserPostGroup(sysUser.getUserName());
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(sysUser);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(sysUser);
            sysUserVo.setPosts(posts);
            sysUserVo.setRoles(roles);
            sysUserVo.setPermissions(permissions);
            if (sysUser.getDeptId() != null) {
                sysUserVo.setDeptId(sysUser.getDeptId());
                SysDept dept_id2 = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", sysUser.getDeptId()));
                sysUserVo.setDeptName(dept_id2.getDeptName());
                //所属单位
                Long orgId = getOrgId(userId);
                SysDept org = sysDeptMapper.selectById(orgId);
                sysUserVo.setDepartmentUnitId(org.getDeptId());
                sysUserVo.setDepartmentUnitName(org.getDeptName());
            }
        }
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("user_id", userId);
        UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper);
        sysUserVo.setUserImage(userInfo.getUserImage());
        sysUserVo.setUsetAddress(userInfo.getUserAddress());
        sysUserVo.setUserPassword(userInfo.getUserPassword());
        sysUserVo.setProvince(userInfo.getProvince());
        sysUserVo.setCity(userInfo.getCity());
        sysUserVo.setArea(userInfo.getArea());
        sysUserVo.setLongitude(userInfo.getLongitude());
        sysUserVo.setLatitude(userInfo.getLatitude());

        sysUserVo.setUserName(sysUser.getUserName());
        return ResultMsg.SELECT_SUCCESS.setNewData(sysUserVo);
    }

    /**
     * @Description 更新用户信息
     * @Author Blq <Br />
     * @Date 9:00 2022/9/5
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     * userAddress: "云南省昆明市官渡区飞虎大道"
     * userImage: "http://yongdianyi.oss-accelerate.aliyuncs.com/2023/01/16/1554d11613f5483a95dddd1d39c7bdd5.jpeg"
     * userNickName: "代熊11111"
     **/
    @Transactional
    @Override
    public ResultMsg updateUser(JSONObject jsonObject) {


        //根据用户id查询userinfo

        String userId = jsonObject.getString("userId");
        if (StringUtils.isBlank(userId)) return ResultMsg.ARGS_ERROR;
        String userImage = jsonObject.getString("userImage");
        if (StringUtils.isBlank(userImage)) return ResultMsg.ARGS_ERROR;
        String userNickName = jsonObject.getString("userNickName");
        if (StringUtils.isBlank(userNickName)) return ResultMsg.ARGS_ERROR;

        UserInfo user_id = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", userId));
        SysUser sysUser1 = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", userId));
        if (user_id == null) return ResultMsg.ENTIY_ERROR;
        //分为首次更改用户信息和其他--1614831143398977538
        if (sysUser1.getDeptId() != 1614831143398977538L) {//其他
            JSONObject sysUser = appMapper.getSysUser(user_id.getUserName());
            if (sysUser == null) return ResultMsg.ENTIY_ERROR;
            appMapper.updateUser(jsonObject);
            jsonObject.put("userName", user_id.getUserName());
            appMapper.updateSysUser(jsonObject);
        } else {//首次
            JSONObject sysUser = appMapper.getSysUser(user_id.getUserName());
            if (sysUser == null) return ResultMsg.ENTIY_ERROR;
            appMapper.updateUser(jsonObject);
            sysUser1.setNickName(userNickName);
            sysUser1.setDeptId(1614830547224801281L);//分配到员工待分配部门
            appMapper.updateSysUser(jsonObject);
            sysUserService.updateUser(sysUser1);
        }
        return ResultMsg.UPDATE_SUCCESS;
    }

    /**
     * @Description 更新用户手机号
     * @Author Blq <Br />
     * @Date 9:18 2022/9/5
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg updateUserPhone(JSONObject jsonObject) {
        String code = RedisUtils.getCacheObject(jsonObject.getString("userName"));
        if (code == null || !code.equals(jsonObject.getString("code"))) {
            return ResultMsg.CODE_ERROR;
        }
        return ResultMsg.UPDATE_SUCCESS.setNewData(appMapper.updateUser(jsonObject));
    }

    /**
     * @Description 更新用户密码
     * @Author Blq <Br />
     * @Date 9:27 2022/9/5
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg updatePassword(JSONObject jsonObject) {
        JSONObject indo = appMapper.getUserIndoById(jsonObject.getString("userId"));
        if (indo == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("查无此信息");
        if (indo.getString("userPassword").equals(jsonObject.getString("userPassword"))) {
            jsonObject.put("userPassword", jsonObject.getString("newPassword"));
            return ResultMsg.UPDATE_SUCCESS.setNewData(appMapper.updateUser(jsonObject));
        }
        return ResultMsg.OBJECT_ERROR.setNewErrorMsg("密码错误");
    }

    /**
     * @Description 用户注册接口
     * @Author Blq <Br />
     * @Date 8:45 2022/9/6
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Transactional
    @Override
    public ResultMsg merchantRegistration(JSONObject jsonObject) {
        //手机号
        String phone = jsonObject.getString("userName");
        if (StringUtils.isBlank(phone)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("手机号不能为空");
        //密码
        String Password = jsonObject.getString("userPassword");
        if (StringUtils.isBlank(Password)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("密码不能为空");
        //验证码
        String usercode = jsonObject.getString("code");
        if (StringUtils.isBlank(usercode)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("验证码不能为空");

        //密码加密
        //根据用户手机号加盐
        /*String faceScore = Md5Utils.md5enc("1");
        String userPassword1 = faceScore + Password;
        String userPassword = Md5Utils.md5enc(userPassword1);*/
        String userPassword = BCrypt.hashpw(Password);

        //验证码校验-1996
        String code = RedisUtils.getCacheObject(jsonObject.getString("userName"));//验证码
        if (StringUtils.isBlank(usercode)) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("验证码已过期,请重新获取验证码");

        if (code.equals(jsonObject.getString("code"))) {//验证码正确
            //幂等

            SysUser sysUser = sysUserMapper.selectOneByphone(phone);
            if (sysUser != null) {
                if (sysUser.getStatus().equals("1") || sysUser.getDelFlag().equals("2")){
                    return ResultMsg.ARGS_ERROR.setNewErrorMsg("您的手机号已注册,但是该账号已停用,请通过管理员启用");
                }
                return ResultMsg.OBJECT_ERROR.setNewErrorMsg("该手机号已注册");
            } else {
                SysUser sysUser1 = new SysUser();
                sysUser1.setUserName(phone);
                sysUser1.setNickName("未设置");
                sysUser1.setPhonenumber(phone);
                long userID = id.nextId();//用户id
                sysUser1.setUserId(userID);
                sysUser1.setAvatar("http://xinxifa.oss-accelerate.aliyuncs.com/2022/08/26/e30e98e7f4d647c4b5f27721b1764dd5.jpg");
                sysUser1.setDelFlag("0");
                sysUser1.setPassword(userPassword);
                sysUser1.setCreateBy("App");
//                sysUser1.setEmail("未设置");
                sysUser1.setFlag("1");//
                sysUser1.setDeptId(1614831143398977538L);
                Date date = new Date();
                sysUser1.setCreateTime(date);
                sysUser1.setStatus("0");
                sysUserMapper.insert(sysUser1);

                UserInfo userInfo = new UserInfo();
                userInfo.setUserName(phone);
                userInfo.setUserPassword(userPassword);
                userInfo.setUserImage("http://xinxifa.oss-accelerate.aliyuncs.com/2022/08/26/e30e98e7f4d647c4b5f27721b1764dd5.jpg");
                userInfo.setUserId(String.valueOf(userID));
                userInfo.setCreateBy("App");
                userInfo.setCreateTime(date);
                userInfo.setUserNickName("未设置");
                userInfo.setUserFlag("1");
                userInfoMapper.insert(userInfo);

                return ResultMsg.INSERT_SUCCESS.setNewErrorMsg("注册成功 !");
            }
        }
        return ResultMsg.OBJECT_ERROR.setNewErrorMsg("验证码错误");
    }

    /**
     * @Description 接口描述 : 商家app软件登录接口（弃用）
     * @Params * @param null
     * userName : 用户手机号
     * userPassword: 用户密码
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 0:02
     */
    @Override
    public ResultMsg merchantLogin(JSONObject jsonObject) {
        //校验
        //用户手机号
        String userName = jsonObject.getString("userName");
        if (StringUtils.isBlank(userName)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户手机号不能为空");
        String Password = jsonObject.getString("userPassword");
        if (StringUtils.isBlank(Password)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户密码不能为空");


        JSONObject info = appMapper.getUserInfoByUserName(userName);
        if (info == null) return ResultMsg.SELECT_ERROR.setNewErrorMsg("查无此信息,请注册");
        //密码加密
        //根据用户手机号加盐
        String faceScore = Md5Utils.md5enc("1");
        String userPassword1 = faceScore + Password;
        String userPassword = Md5Utils.md5enc(userPassword1);
        if (info.getString("userPassword").equals(userPassword)) {
            return ResultMsg.LOGIN_SUCCESS.setNewData(info);
        }

        return ResultMsg.OBJECT_ERROR.setNewErrorMsg("密码错误");
    }

    @Override
    public JSONObject getUserInfo(String userName) {
        return appMapper.getUserInfoByUserName(userName);
    }

    /**
     * @Description 获取我的工单
     * @Author Blq <Br />
     * @Date 8:57 2022/9/6
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg myTickets(JSONObject jsonObject) {

        List<JSONObject> jsonObjectList = appMapper.getTicketsById(jsonObject);
        if (jsonObjectList == null || jsonObjectList.size() == 0) {
            jsonObjectList = new ArrayList<>();
        }
        return ResultMsg.SELECT_SUCCESS.setNewData(jsonObjectList);
    }

    /**
     * @Description 接口描述 : 查看我的待办理订单
     * @Params * @param null
     * loginmanId :1023995635902185472----登录人的id
     * @Return
     * @Author xiaw
     * @Date 2022/12/24 23:58
     */
    @Override
    public ResultMsg ticketPool(JSONObject Object) {

        String loginmanId = Object.getString("loginmanId");//登录人id
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("当前登录人不能为空");
        //查询待处理订单
        LinkedHashSet<JSONObject> jsonObjects = selelctPending(loginmanId);
        if (jsonObjects.size() == 0) {
            return ResultMsg.SUCCESS.setNewErrorMsg("暂时没有您的相关订单");
        } else {
            return ResultMsg.SELECT_SUCCESS.setNewData(jsonObjects);
        }
    }

    /**
     * @Description 接口描述 : 查询待处理订单
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/27 16:01
     */
    public LinkedHashSet<JSONObject> selelctPending(String loginmanId) {

        //去重集合
        LinkedHashSet<JSONObject> jsonObjects1 = new LinkedHashSet<>();
        //根据登录人id去分辨是用户还是
        String userFlag = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", loginmanId).select("user_flag")).getUserFlag();

        ArrayList<String> strings1 = roleJudgment(loginmanId);
        for (String role : strings1) {
            if (role.equals("平台客户") && userFlag.equals("0")) {
                //@todo
            } else {
                //公司id
                Long aLong = getOrgId(loginmanId);
                if (role.equals("分公司经理")&& userFlag.equals("1")) {
                }
                if (role.equals("分公司接待部门负责人")&& userFlag.equals("1")) {

                }
                if (role.equals("分公司运维部门负责人")&& userFlag.equals("1")) {
                    //查看审核表审核人有自己的数据,并且审核结果ticket_reslover是2 的单子
                    QueryWrapper<Ticket> ticketQueryWrapper1 = new QueryWrapper<>();
                    ticketQueryWrapper1.eq("ticket_reviewer", loginmanId);
                    ticketQueryWrapper1.eq(false, "ticket_reslover", "0");
                    List<Ticket> tickets1 = ticketMapper.selectList(ticketQueryWrapper1);
                    for (Ticket ticket : tickets1) {
                        JSONObject CustomerRepair = customerRepairMapper.selectByCustomerKeyw(ticket.getTicketRepair());
                        if (CustomerRepair != null) jsonObjects1.add(CustomerRepair);
                    }

                }
                if (role.equals("分公司财务")&& userFlag.equals("1")) {
                    //公司所有订单
                    List<CustomerRepair> companyList = customerRepairMapper.selectListByCompany(String.valueOf(aLong), "11");
                    for (CustomerRepair customerRepair : companyList) {
                        JSONObject jsonObject = appMapper.ticketsPoolOrderId(customerRepair.getCustomerKey());
                        if (jsonObject.size() != 0) jsonObjects1.add(jsonObject);
                    }
                }
                if (role.equals("分公司施工人员")&& userFlag.equals("1")) {
                    //工人查看待处理订单
                    List<JSONObject> jsonObjects = appMapper.ticketsPool(loginmanId, aLong);
                    setPendingOrder(jsonObjects1, jsonObjects);
                }
                if (role.equals("分公司电站人员")&& userFlag.equals("1")) {
                    //根据公司id和订单状态查找
                    List<CustomerRepair> companyList = customerRepairMapper.selectListBypowerPlant(String.valueOf(aLong));
                    for (CustomerRepair customerRepair : companyList) {
                        JSONObject jsonObject = appMapper.ticketsPoolOrderId(customerRepair.getCustomerKey());
                        if (jsonObject.size() != 0) jsonObjects1.add(jsonObject);
                    }
                }
            }
        }

        return jsonObjects1;
    }

    //待处理
    private void setPendingOrder(LinkedHashSet<JSONObject> jsonObjects1, List<JSONObject> jsonObjects) {
        for (JSONObject jsonObject : jsonObjects) {
            if (jsonObject != null) jsonObjects1.add(jsonObject);
        }
    }

    /**
     * @Description 获取全部单位
     * @Author Blq <Br />
     * @Date 10:55 2022/9/6
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg getDepts(JSONObject jsonObject) {
        String parent_id = jsonObject.getString("parentId");//100

        String deptName = jsonObject.getString("deptName");//服务机构名字
        if (deptName != null || parent_id != null) {
            List<JSONObject> allDepts = appMapper.getAllDepts(jsonObject);
            return ResultMsg.SELECT_SUCCESS.setNewData(allDepts);
        }
        return ResultMsg.ARGS_ERROR.setNewErrorMsg("不能两个参数都为空");
    }

    @Override
    public ResultMsg getDept(String deptId) {
        return ResultMsg.SELECT_SUCCESS.setNewData(sysDeptMapper.selectone(deptId));
    }

    /**
     * @Description 获取部门下人员
     * @Author Blq <Br />
     * @Date 11:04 2022/9/6
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg getDeptUser(JSONObject jsonObject) {
        String deptId = jsonObject.getString("deptId");//传入一个部门id.查询该不部门下的所有员工
        if (StringUtils.isBlank(deptId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("部门id不能为空");
        SysDept sysDept = sysDeptMapper.selectById(deptId);
        List<SysUser> sysUsers = sysUserMapper.selectByRootDept(deptId, sysDept.getAncestors());
        return ResultMsg.SELECT_SUCCESS.setNewData(sysUsers);
    }

    /**
     * @Description 接口描述 : 新增审核资料
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 0:34
     */
    @Transactional
    @Override
    public ResultMsg ticketReview(@org.jetbrains.annotations.NotNull JSONObject jsonObject) {
        //部门id--ticketUser
        String ticketRepair = jsonObject.getString("ticketRepair");
        String ticketTime = jsonObject.getString("ticketTime");
        String loginmanId = jsonObject.getString("loginmanId");
        String ticketDept = jsonObject.getString("ticketDept");
        String ticketUser = jsonObject.getString("ticketUser");
        String ticketEquip = jsonObject.getString("ticketEquip");
        String ticketCar = jsonObject.getString("ticketCar");
        String ticketCircumstance = jsonObject.getString("ticketCircumstance");
        if (StringUtils.isBlank(ticketDept)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("部门id不能为空");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人不能为空");
        if (StringUtils.isBlank(ticketRepair)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单不能为空");
        if (StringUtils.isBlank(ticketTime)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("时间不能为空");

        //数据准备
        //  部门处理---(单人多人处理)
//        String companyid = getCompanyId(loginmanId);
        String replace = null;

        if (ticketUser != null) {
            LinkedHashSet<String> superiorDepartment = new LinkedHashSet<>();
            String[] strings = ticketUser.split(",");//员工的id

            for (String string : strings) {
                Long orderId = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", Long.parseLong(string))).getDeptId();
                superiorDepartment.add(String.valueOf(orderId));
            }
            String s = superiorDepartment.toString();
            String substring = s.substring(1, s.length() - 1);
            replace = substring.replace(" ", "");
        }
        Date date = new Date();
        //  判断订单类型
//        String determineAssignmentType = getDetermineAssignmentType(ticketRepair);
        //根据登录人去得到审核人
        /*Long deptId = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", loginmanId)).getDeptId();
        String aLong = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", deptId)).getLeader();*/
        //根据工单匹配合适的审核人
        String reviewer = getReviewer(ticketRepair);
        if (StringUtils.isBlank(reviewer)) {
            return ResultMsg.ARGS_ERROR.setNewErrorMsg("未分配到合适的审核人员，请联系管理人员。");
        }
        //审核对象--准备
        Ticket ticket1 = ticketMapper.selectOne(new QueryWrapper<Ticket>()
                .eq("ticket_repair", ticketRepair));
        if (ticket1 == null) {
            ticket1 = new Ticket();
            ticket1.setCreateBy(loginmanId);//创建人
            ticket1.setCreateTime(date);
        }
        ticket1.setTicketRepair(ticketRepair);//工单号
        ticket1.setTicketTime(date);//上门时间
        ticket1.setTicketCircumstance(ticketCircumstance);//作业基本情况
        ticket1.setTicketDept(replace);//人员部门id
        ticket1.setTicketUser(ticketUser);//工人
        ticket1.setTicketEquip(ticketEquip);//装备
        ticket1.setTicketCar(ticketCar);//车辆
//        ticket1.setTicketKey(String.valueOf(id.nextId()));//随机主键
        ticket1.setTicketReviewer(String.valueOf(reviewer));//审核人
        ticket1.setTicketReslover("2");//未审核
        if (StringUtils.isBlank(ticket1.getTicketKey())) {
            ticketMapper.insert(ticket1);
        } else {
            ticketMapper.updateById(ticket1);
        }
        /*if (determineAssignmentType.equals("2")) { //自定义指派
            //自定义指派-每次都是修改审核信息
            ticket1.setTicketUser(ticketUser);

            //自定义指派会提前创建审核表相关信息---根据审核时间判断是否是第一次提交
            Ticket ticket_repair = ticketMapper.selectOne(new QueryWrapper<Ticket>()
                    .eq("ticket_repair", ticketRepair));
            UpdateWrapper<Ticket> ticketUpdateWrapper = new UpdateWrapper<>();
            ticketUpdateWrapper.eq("ticket_repair", ticketRepair);
            if (StringUtils.isBlank(ticket_repair.getTicketReslover()) || ticket_repair.getTicketReslover().equals("1")) {//如果有审核结果
                ticket1.setTicketReslover("2");//不是首次提交-
            } else {
                ticket1.setCreateBy(loginmanId);//创建人
                ticket1.setTicketReviewer(String.valueOf(reviewer));//审核人
                ticket1.setCreateTime(date);
            }
            ticketMapper.update(ticket1, ticketUpdateWrapper);//首次提交

        } else {//自动指派
            //根据工单号去查审核信息
            List<Ticket> ticket_repair = ticketMapper.selectList(new QueryWrapper<Ticket>().eq("ticket_repair", ticketRepair));
            if (ticket_repair.size() > 0) {
                //说明是第二次提交审核
                ticket1.setTicketUser(ticketUser);
                ticket1.setTicketReslover("2");
                appMapper.updaTeticketByOrderId(ticket1);
            } else {//首次提交审核
                ticket1.setTicketUser(ticketUser);//工人
                ticket1.setTicketKey(String.valueOf(id.nextId()));
                ticket1.setTicketReviewer(String.valueOf(reviewer));//审核人
                ticket1.setCreateBy(loginmanId);//创建人
                ticket1.setCreateTime(date);
                ticketMapper.insert(ticket1);
            }
        }*/
        // 更新工单状态
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(ticketRepair);
        customerRepair.setCustomerFlag("8");
        customerRepair.setWaitExamineTime(date);//上传审核时间
        customerRepair.setReceiverBy(ticketUser);
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);

        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(ticketRepair);
        SysUser smsUser = sysUserMapper.selectById(reviewer);
        if (smsUser != null) {
            SendOrderMsg.sendDIY("提醒：您有一份<" + order.getCustomerHelp() + ">订单待审批，请尽快处理。", smsUser.getPhonenumber());
        }
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单已提交审核，可前往小程序查看详情。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告
        //更新公告信息
//        String orderType = customerRepairServiceimpl.maintenanceType(ticketRepair);//订单名字--参数是工单号
        String content = "尊敬的用户 : 你好 ,您的" + order.getCustomerHelp() + "提交了审核信息,点击订单查看详情!";
        String remark = "备注";

        //传入登录人id ,工单id.备注.公告内容
        customerRepairServiceimpl.updateNotice(loginmanId, ticketRepair, remark, content, "0", null, "0", null);
        return ResultMsg.SELECT_SUCCESS;
    }

    /**
     * 根据工单获取对应审核人*
     * @param orderId
     * @return
     */
    private String getReviewer(String orderId) {
        CustomerRepair order = customerRepairMapper.selectById(orderId);
        String customerAddress = order.getCustomerAddress();
        String deptId = order.getCompanyId();
        /*for (SysDept sysDept : sysDeptMapper.selectListDept(order.getCompanyId(), "1")) {
            if (StringUtils.isNotBlank(sysDept.getCity()) && customerAddress.contains(sysDept.getCity().substring(0,2))){
                deptId = sysDept.getDeptId().toString();
            }
        }*/
        List<SysUser> users = sysUserMapper.selectWorkerByDept(deptId, "audit_order");
        if (users.size() > 0) {
            return users.get(0).getUserId().toString();
        }
        /*List<SysUser> users = sysUserMapper.selectWorkerByDept(order.getCompanyId(), "audit_order");
        if (users.size() > 0) {
            for (SysUser user : users) {
                if (customerAddress.contains(user.getDept().getCity().substring(0,2))){
                    return user.getUserId().toString();
                }
            }
            return users.get(0).getUserId().toString();
        }*/
        return null;
    }

    //判断订单 是不是自定义指派--判断指派类型
    public String getDetermineAssignmentType(String ticketRepair) {
        String customerAuto = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                .eq("customer_key", ticketRepair)
                .select("customer_auto")).getCustomerAuto();
        return customerAuto;
    }

    /**
     * @Description 查询工单状态
     * @Author Blq <Br />
     * @Date 9:12 2022/9/7
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg getTicketRow(@NotNull JSONObject jsonObject) {
        if (StringUtils.isBlank(jsonObject.getString("status"))) return ResultMsg.ARGS_ERROR;
        // 待审核
        if ("3".equals(jsonObject.getString("status"))) {
            JSONObject repair = appMapper.selectTickets(jsonObject.getString("ticketRepair"));
            return ResultMsg.OBJECT_SUCCESS.setNewData(repair);
        }
        // 勘察资料
        if ("9".equals(jsonObject.getString("status"))) {
            JSONObject repair = appMapper.getInvestigationMessage(jsonObject.getString("ticketRepair"));
            return ResultMsg.SELECT_SUCCESS.setNewData(repair);
        }
        // 报价信息
        if ("1".equals(jsonObject.getString("status"))) {
            JSONObject ticketRepair = appMapper.getAuotation(jsonObject.getString("ticketRepair"));
            return ResultMsg.SELECT_SUCCESS.setNewData(ticketRepair);
        }
        // 查询收款信息
        if ("5".equals(jsonObject.getString("status"))) {
            JSONObject payOutInfo = appMapper.getPayOutInfo();
            return ResultMsg.SELECT_SUCCESS.setNewData(payOutInfo);
        }
        return ResultMsg.OBJECT_SUCCESS.setNewData(appMapper.getTicketById(jsonObject.getString("ticketRepair")));
    }

    /**
     * @Description 接口描述 : 师傅端个人中心-查看待接单按钮
     * @Params * @param
     * status :
     * 个人中心查看订单接口 : 待接单 :0/已接单 :21/待审核 : 8/待勘察 :9/待报价 :1/签单 :/待施工 :3/待验收 :4/待付款 :5/财务确认 :11/已付款 :10/已完成 :7/已关闭 :7/
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 0:06
     */
    @Override
    public ResultMsg myTicketsMy(JSONObject jsonObject) {


        //8-待审核--只有审核人员能看
        String status = jsonObject.getString("status");
        String userId = jsonObject.getString("userId");
        //公司id
        Long aLong = getOrgId(userId);
        //去重集合
        LinkedHashSet<CustomerRepair> customerRepairs = new LinkedHashSet<>();

        ArrayList<String> strings1 = roleJudgment(userId);
        for (String string : strings1) {
            if (Objects.equals(string, "平台客户")) {
                if (status.equals("0")) {

                    //条件
                    QueryWrapper<CustomerRepair> wrapper = new QueryWrapper<>();
                    wrapper.eq("customer_id", userId);
                    wrapper.orderByDesc("create_time");
                    wrapper.and(customerRepairQueryWrapper -> customerRepairQueryWrapper
                            .eq("customer_flag", "99").or().eq("customer_flag", "0"));
                    //查询-用户的待接单展示待接单和工单池订单
                    List<CustomerRepair> customerRepairList = customerRepairMapper.selectList(wrapper);
                    setpersonageOrder(customerRepairs, customerRepairList);
                }
                //用户的其他状态订单
                List<CustomerRepair> customerRepairList = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>()
                        .eq("customer_flag", status)
                        .eq("customer_id", userId)
                        .orderByDesc("create_time"));
                setpersonageOrder(customerRepairs, customerRepairList);
            } else {

                //该状态该公司所有的订单
                List<CustomerRepair> customerRepairList = customerRepairMapper
                        .selectList(new QueryWrapper<CustomerRepair>()
                                .eq("company_id", aLong)
                                .eq("customer_flag", status)
                                .orderByDesc("create_time"));

                if (Objects.equals(string, "分公司施工人员")) {//查看自己的订单
                    List<CustomerRepair> customerRepairList1 = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>()
                            .eq("customer_flag", status).like("receiver_by", userId));
                    setpersonageOrder(customerRepairs, customerRepairList1);
                }

                if (Objects.equals(string, "分公司运维部门负责人")) {

                    //查到该审核人员不是不同意的审核订单
                    QueryWrapper<Ticket> ticketQueryWrapper = new QueryWrapper<>();
                    ticketQueryWrapper.orderByDesc("create_time");
                    ticketQueryWrapper.eq("ticket_reviewer", userId);
                    ticketQueryWrapper.eq("ticket_reslover", "2");
                    List<Ticket> tickets1 = ticketMapper.selectList(ticketQueryWrapper);

                    for (Ticket ticket : tickets1) {
                        CustomerRepair customerRepair = customerRepairMapper.selectone(ticket.getTicketRepair(), status);
                        if (customerRepair != null) customerRepairs.add(customerRepair);
                    }
                }
                if (Objects.equals(string, "分公司财务")) {

                    //完成的订单
                    if (status.equals("7")) {
                        //公司所有订单
                        List<CustomerRepair> companyList = customerRepairMapper.selectListByCompany(String.valueOf(aLong), status);
                        if (companyList.size() != 0) companyList.forEach(a -> customerRepairs.add(a));
                    }

                    //待财务确认订单
                    if (status.equals("11")) {
                        List<CustomerRepair> companyList = customerRepairMapper.selectListByCompany(String.valueOf(aLong), status);
                        if (companyList.size() != 0) companyList.forEach(a -> customerRepairs.add(a));
                    }
                }
                //分公司电站人员查看订单--状态未知--暂时不需要
                if (Objects.equals(string, "分公司电站人员") && status.equals("7")) {
                    //查看已完成的订单
                    //公司所有订单
                    List<CustomerRepair> customerRepairList1 = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>()
                            .eq("company_id", aLong)
                            .eq("searchable", "2"));
                    setpersonageOrder(customerRepairs, customerRepairList1);
                }
            }
        }
        if (customerRepairs.size() == 0) return ResultMsg.SUCCESS.setNewErrorMsg("暂时没有你的订单");
        return ResultMsg.OBJECT_SUCCESS.setNewData(customerRepairs);
    }

    //set个人订单
    private void setpersonageOrder(LinkedHashSet<CustomerRepair> customerRepairs, List<CustomerRepair> customerRepairList1) {
        for (CustomerRepair customerRepair : customerRepairList1) {
            if (customerRepair != null) customerRepairs.add(customerRepair);
        }
    }

    /**
     * @Author: xiaw
     * 根据订单id和用户id填充集合
     */
    private LinkedHashSet<CustomerRepair> checkAnOrder(String status, String userId, LinkedHashSet<CustomerRepair> customerRepairs, Long along) {
        //用户的
        QueryWrapper<CustomerRepair> wrapper = new QueryWrapper<>();
        wrapper.eq("customer_flag", status);
        wrapper.eq("customer_id", userId);
        List<CustomerRepair> list = customerRepairMapper.selectList(wrapper);
        if (list.size() != 0) list.forEach(a -> customerRepairs.add(a));
        //审核人员的
        QueryWrapper<Ticket> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("ticket_reviewer", userId);
        List<Ticket> tickets1 = ticketMapper.selectList(wrapper1);
        for (Ticket ticket : tickets1) {
            QueryWrapper<CustomerRepair> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("customer_flag", status);
            wrapper.eq("company_id", along);
            wrapper2.eq("customer_key", ticket.getTicketRepair());
            CustomerRepair customerRepair = customerRepairMapper.selectOne(wrapper2);
            if (customerRepair != null) customerRepairs.add(customerRepair);
        }
        //师傅的
        QueryWrapper<CustomerRepair> wrapper4 = new QueryWrapper<>();
        wrapper4.eq("customer_flag", status);//状态
        wrapper4.eq("company_id", along);//公司id
        wrapper4.like("receiver_by", userId);
        List<CustomerRepair> list5 = customerRepairMapper.selectList(wrapper4);
        //订单
        if (list5.size() != 0) list5.forEach(a -> customerRepairs.add(a));
        //审核相关
        for (CustomerRepair customerRepair : list5) {
            QueryWrapper<Ticket> ticketQueryWrapper = new QueryWrapper<>();
            ticketQueryWrapper.like("ticket_user", userId);
            ticketQueryWrapper.eq("ticket_repair", customerRepair.getCustomerKey());
            Ticket ticket = ticketMapper.selectOne(ticketQueryWrapper);
            if (ticket != null) customerRepairs.add(customerRepair);
        }
        return customerRepairs;
    }

    /**
     * @Description 审核请求
     * @Author Blq <Br />
     * @Date 10:37 2022/9/7
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg approveRequest(JSONObject jsonObject) {
        Date date = new Date();
        //工单id
        String orderId = jsonObject.getString("id");
        String Ticketremark = jsonObject.getString("remark");
        JSONObject ticket = appMapper.getTicketById(orderId);
        if (ticket == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("工单信息错误");
        String loginmanId1 = jsonObject.getString("loginmanId");
        //审核对象
        Ticket ticket1 = new Ticket();
        ticket1.setTicketRepair(orderId);
        ticket1.setRemark(Ticketremark);
        //工单对象
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setExamineTime(date);
        customerRepair.setUpdateBy(loginmanId1);
        customerRepair.setUpdateTime(date);

        if ("0".equals(jsonObject.getString("status"))) { // 同意
            ticket1.setTicketReslover("0");
            customerRepair.setCustomerKey(orderId);
            customerRepair.setCustomerFlag("9");
        } else if ("1".equals(jsonObject.getString("status"))) {//不同意
            ticket1.setTicketReslover("1");
            customerRepair.setCustomerKey(orderId);
            customerRepair.setCustomerFlag("21");
        }
        appMapper.updaTeticketByOrderId(ticket1);
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);

        String result = "0".equals(jsonObject.getString("status")) ? "已审核通过" : "审核不通过";
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(orderId);
        SysUser smsUser = sysUserMapper.selectById(order.getReceiverBy().split(",")[0]);
        if (smsUser != null) {
            SendOrderMsg.sendDIY("提醒：您有一份<" + order.getCustomerHelp() + ">订单" + result + "，请尽快处理。", smsUser.getPhonenumber());
        }
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单已审核结束，可前往小程序查看详情。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告信息
//        String orderType = customerRepairServiceimpl.maintenanceType(orderId);//订单名字--参数是工单号
//        String result = "0".equals(jsonObject.getString("status")) ? "审核通过" : "审核不通过";
        String content = "尊敬的用户 : 你好 ,您的" + order.getCustomerHelp() + result + "点击订单查看详情!";
        customerRepairServiceimpl.updateNotice(loginmanId1, orderId, "备注", content, "0", "0", null, null);
        return ResultMsg.SUCCESS;
    }

    /**
     * @Description 新增工单下勘察资料
     * @Author Blq <Br />
     * @Date 8:56 2022/9/8
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Transactional
    @Override
    public ResultMsg addInvestigation(JSONObject jsonObject) {
        Date date = new Date();
        //判断不拉不拉
        //工单号
        String investigationRepari = jsonObject.getString("investigationRepari");
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(investigationRepari)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");
        //资产判定类型
        String investigationProperty = jsonObject.getString("investigationProperty");
        if (StringUtils.isBlank(investigationProperty)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("资产判定不能为空");
        //勘察图片不能为空
        String investigationImages = jsonObject.getString("investigationImages");
        if (StringUtils.isBlank(investigationImages)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("图片不能为空不能为空");
        if (!investigationProperty.equals("1")) {
            return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号设计的资产不属于客户产权,请确认是否关闭订单");
        }
        //幂等
        //根据订单号去勘察资料表里面去查是否有该数据
        Investigation investigation_repari = investigationMapper.selectOne(new QueryWrapper<Investigation>().eq("investigation_repari", investigationRepari));
//        MaterialInfo material_repari = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>().eq("material_repari", investigationRepari));

        if (investigation_repari == null/* && material_repari == null*/) {
            jsonObject.put("investigationKey", id.nextId());
            JSONObject repari = appMapper.getTicketById(jsonObject.getString("investigationRepari"));
            if (repari == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("查无此订单信息");
            CustomerRepair customerRepair = new CustomerRepair();
            customerRepair.setCustomerKey(investigationRepari);
            customerRepair.setCustomerFlag("1");
            customerRepair.setSurveyTime(date);
            customerRepair.setUpdateBy(loginmanId);
            customerRepair.setUpdateTime(date);
            customerRepairMapper.updateCustomerRepairBykey(customerRepair);
            appMapper.addInvestigation(jsonObject);

//            MaterialInfo materialInfo = new MaterialInfo();
//            materialInfo.setMaterialRepari(investigationRepari);
//            materialInfo.setFaultCondition(jsonObject.getString("investigationContent"));
//            materialInfoMapper.insert(materialInfo);

            //同步施工图片
            String[] split = investigationImages.split(",");
            for (String s : split) {
                MaterialBefore materialBefore = new MaterialBefore();
                materialBefore.setMaterialRepari(investigationRepari);
//                materialBefore.setIds("null");
                materialBefore.setIds(jsonObject.getString("investigationKey"));
                materialBefore.setMaterialBefore(s);
                materialBeforeMapper.insertt(materialBefore);
            }
            /*ArrayList<String> materialAfterstring = new ArrayList<>();
            for (int i = 0; i <= split.length - 1; i++) {
                materialAfterstring.add(split[i]);
            }
            MaterialBefore materialBefore = new MaterialBefore();
            materialBefore.setMaterialRepari(investigationRepari);
            materialBefore.setIds("null");
            for (String s : materialAfterstring) {
                materialBefore.setMaterialBefore(s);
                materialBeforeMapper.insertt(materialBefore);
            }*/
            //短信提醒
            CustomerRepair order = customerRepairMapper.selectById(investigationRepari);
            if (StringUtils.isNotBlank(order.getCustomerPhone())) {
                SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单提交了勘察信息，可前往小程序查看详情。", order.getCustomerPhone(), order.getLiaisonPhone());
            }
            //更新公告
//            String orderType = customerRepairServiceimpl.maintenanceType(investigationRepari);//订单名字--参数是工单号
            String content = "尊敬的用户 : 你好 ,您的" + order.getCustomerHelp() + "提交了勘察信息,点击订单查看详情!";
            customerRepairServiceimpl.updateNotice(null, investigationRepari, "备注", content, "0", null, null, null);
            return ResultMsg.SUCCESS.setNewErrorMsg("提交成功 !");
        }
        return ResultMsg.ARGS_ERROR.setNewErrorMsg("订单已存在,请勿重复提交 !");
    }

    /**
     * @Description 新增报价单
     * @Author Blq <Br />
     * @Date 9:28 2022/9/8
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Transactional
    @Override
    public ResultMsg addAuotation(JSONObject jsonObject) {
        String orderid = jsonObject.getString("quotationRepair");//工单号
        String quotationAudtio = jsonObject.getString("quotationAudtio");        //方案和报价
        String quotationInformation = jsonObject.getString("quotationInformation");        //客户上传资料
        String loginmanId = jsonObject.getString("loginmanId");        //登录人
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人id不能为空");
        if (StringUtils.isBlank(orderid)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");
        if (StringUtils.isBlank(quotationAudtio)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("方案和报价不能为空");

        Date date = new Date();
        //新增合同信息幂等
        List<Quotation> quotation_repair = quotationMapper.selectList(new QueryWrapper<Quotation>().eq("quotation_repair", orderid));
        if (quotation_repair.size() != 0) return ResultMsg.ARGS_ERROR.setNewErrorMsg("合同信息已存在,请勿重复提价");
        //新增合同信息
        Quotation quotation = new Quotation();
        quotation.setQuotationAudtio(quotationAudtio);//方案和报价
        quotation.setQuotationInformation(quotationInformation);//客户上传资料
        quotation.setQuotationKey(String.valueOf(id.nextId()));//id自增
        quotation.setQuotationRepair(orderid);
        quotation.setCreateTime(date);
        quotationMapper.insert(quotation);
        //修改订单信息--更新创报价的时间
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(orderid);
        customerRepair.setOfferTime(date);
        customerRepair.setCustomerFlag("98");//工单进入待签单状态

        customerRepairMapper.updateCustomerRepairBykey(customerRepair);//修改工单信息

        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(orderid);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单提交了报价信息，可前往小程序查看详情。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告
        String orderType = customerRepairServiceimpl.maintenanceType(orderid);//订单名字--参数是工单号
        String content = "尊敬的用户 : 你好 ,您的" + orderType + "提交了报价信息,点击订单查看详情!";
        String remark = "备注";
        //传入登录人id ,工单id.备注.公告内容
        customerRepairServiceimpl.updateNotice(loginmanId, orderid, remark, content, "0", null, null, null);
        return ResultMsg.OBJECT_SUCCESS.setNewErrorMsg("新增报价成功");
    }

    /**
     * @Description 接口描述 : 客户签单接口
     * @Params * @param quotation_scmor合同/quotation_price价格
     * @Return
     * @Author xiaw
     * @Date 2023/1/2 17:41
     */
    @Transactional
    @Override
    public ResultMsg SignCcontract(JSONObject jsonObject) {

        //判断不拉不拉
        Date date = new Date();
        //价格
        String quotationPrice = jsonObject.getString("quotationPrice");
        if (StringUtils.isBlank(quotationPrice)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("价格不能为空");
        //合同
        String quotationScmor = jsonObject.getString("quotationScmor");
        if (StringUtils.isBlank(quotationScmor)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("合同信息不能为空");
        //工单号
        String quotationRepair = jsonObject.getString("quotationRepair");
        if (StringUtils.isBlank(quotationRepair)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");
        //登录人
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人不能为空");
        //收款部门ID
        String payoutFrom = jsonObject.getString("payoutFrom");
        //复电时间
        String materialTime = jsonObject.getString("materialTime");

        //填入合同价格和合同
        appMapper.updateByQuotationRepair(quotationRepair, quotationPrice, quotationScmor);
        //修改订单状态
        UpdateWrapper<CustomerRepair> wrapper1 = new UpdateWrapper<>();
        boolean b = EqName(quotationRepair);
        wrapper1.eq("customer_key", quotationRepair);
        wrapper1.set("sign_time", date);
        if (StringUtils.isNotBlank(materialTime)) {
            wrapper1.set("material_time", materialTime);
        }
        if (!b) {
            //非保修
            wrapper1.set("customer_flag", "3");//待施工

        } else {//报修
            wrapper1.set("customer_flag", "5");//待付款
//            wrapper1.set("customer_flag", "10");//待付款
//            String open = sysConfigService.selectConfigByKey("order.worker.open");
//            if ("100".equals(payoutFrom) && "yes".equals(open)) {
                // 该订单需要分账
                wrapper1.set("payoff_state", 0);
//            }
        }
        //新增支付订单幂等
        List<PayoutInformation> customer_key = payoutInformationMapper.selectList(new QueryWrapper<PayoutInformation>().eq("customer_key", quotationRepair));
        if (customer_key.size() != 0) return ResultMsg.ARGS_ERROR.setNewErrorMsg("该付款单信息已存在");
        SysDept payoutFromDept = sysDeptMapper.selectone(payoutFrom);
        //新增支付订单
        PayoutInformation payoutInformation = new PayoutInformation();
        payoutInformation.setPayoutKey(String.valueOf(id.nextId()));
        payoutInformation.setCustomerKey(quotationRepair);
        payoutInformation.setCreateBy(loginmanId);//创建者
        payoutInformation.setCreateTime(new Date());
        payoutInformation.setPaymentStatus("0");//未付款
        payoutInformation.setPayoutPrice(new BigDecimal(quotationPrice));
        payoutInformation.setPayoutFrom(payoutFromDept.getDeptName());
        payoutInformation.setPayoutFromId(payoutFrom);
        int insert = payoutInformationMapper.insert(payoutInformation);
        boolean update = customerRepairServiceimpl.update(wrapper1);
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(quotationRepair);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            if (b) {
                String message = "尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单提交了合同信息";
                if (StringUtils.isNotBlank(materialTime)) {
                    message = message + "，预计复电时间：" + materialTime;
                }
                message = message + "，请前往微信小程序线上缴费以继续完成订单。";
                SendOrderMsg.sendDIY(message, order.getCustomerPhone(), order.getLiaisonPhone());
            } else {
                SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单提交了合同信息，师傅即将开始施工，请您耐心等待。", order.getCustomerPhone(), order.getLiaisonPhone());
            }
        }
        //更新公告
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(quotationRepair);//订单名字--参数是工单号
        String content = "尊敬的用户 : 你好 ,您的" + orderType + "提交了合同信息,点击订单查看详情!";
        String remark = "备注";
        //传入登录人id ,工单id.备注.公告内容
        customerRepairServiceimpl.updateNotice(loginmanId, quotationRepair, remark, content, "0", null, null, null);

        return ResultMsg.SUCCESS.setNewErrorMsg("合同签订的成功");

    }

    /**
     * 修改报价和合同信息
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResultMsg updateQuotation(JSONObject jsonObject) {
//        String quotationKey = jsonObject.getString("quotationKey");
        String quotationPrice = jsonObject.getString("quotationPrice");
        //工单号
        String quotationRepair = jsonObject.getString("quotationRepair");
        if (StringUtils.isBlank(quotationRepair)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");
        appMapper.updateByQuotationRepair2(jsonObject);
        payoutInformationService.update(new UpdateWrapper<PayoutInformation>()
                .eq("customer_key", quotationRepair)
                .set("payout_price", quotationPrice));
        return ResultMsg.SUCCESS.setNewErrorMsg("操作成功");
    }

    /**
     * 客户通过微信付款(生成微信付款订单信息给前端)
     * @param jsonObject
     * @return
     */
    @Override
    public ResultMsg userPaymentOrder(JSONObject jsonObject) {
        //工单号
        String orderId = jsonObject.getString("orderId");
        if (StringUtils.isBlank(orderId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");
        //登录人
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人不能为空");
        CustomerRepair customerRepair = customerRepairMapper.selectById(orderId);
        if (customerRepair == null) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("订单不存在");
        }
        if (!"5".equals(customerRepair.getCustomerFlag())) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("此订单当前不是待付款阶段");
        }
        PayoutInformation payout = payoutInformationMapper.selectOne(new QueryWrapper<PayoutInformation>().eq("customer_key", orderId));
        if (payout == null || "1".equals(payout.getPaymentStatus())) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("此订单已付款，请勿重复付款");
        }
        try {
            return wxPayService.pay(payout.getPayoutPrice().doubleValue(), 3, loginmanId, orderId);
        } catch (Exception e) {
            return ResultMsg.OBJECT_ERROR.setNewErrorMsg("生成付款信息失败");
        }
    }

    /**
     * 现场付款、客户付款
     * @param jsonObject
     * @return
     */
    @Transactional
    @Override
    public ResultMsg userSubmitPayment(JSONObject jsonObject){
        //工单号
        String orderId = jsonObject.getString("orderId");
        if (StringUtils.isBlank(orderId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");
        //付款方式
        String paymentMethod = jsonObject.getString("paymentMethod");
        if (StringUtils.isBlank(paymentMethod)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("付款方式不能为空");
        //登录人
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人不能为空");
        String formatdate = time.format(new Date());
        //更新付款信息
        payoutInformationMapper.updateByOrderId3(orderId, formatdate, paymentMethod);
        //更新工单状态为待确认收款
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(orderId);
        customerRepair.setCustomerFlag("10");
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(orderId);
        SysUser smsUser = sysUserMapper.selectById(order.getReceiverBy().split(",")[0]);
        SendOrderMsg.sendDIY("提醒：您有一份<" + order.getCustomerHelp() + ">订单待确认收款，请尽快处理。", smsUser.getPhonenumber());
//        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
//            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单提交了付款信息，待师傅确认收款，请您耐心等待。", order.getCustomerPhone(), order.getLiaisonPhone());
//        }
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(orderId);//订单名字--参数是工单号
        String content = "尊敬的用户 : 你好 ,您的" + orderType + "工单提交了付款信息，待师傅确认收款，请您耐心等待 !";
        customerRepairServiceimpl.updateNotice(loginmanId, orderId, "备注", content, null, "0", null, null);
        return ResultMsg.UPDATE_SUCCESS.setNewErrorMsg("已提交付款信息，等待师傅确认收款");
    }

    /**
     * @Description 接口描述 :确认收款
     * @Params * @param null
     * id : 工单id
     * @Return
     * @Author xiaw
     * @Date 2022/12/26 16:52
     */
    @Override
    public ResultMsg confirmationOfReceipt(JSONObject jsonObject) {
        String formatdate = time.format(new Date());
        String orderId = jsonObject.getString("id");
        String loginmanId = jsonObject.getString("loginmanId");
        String paymentMethod = jsonObject.getString("paymentMethod");
        String message = null;
        CustomerRepair order = customerRepairMapper.selectById(orderId);
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(orderId);
        if (EqName(orderId)) {
            //保修订单
            if ("5".equals(order.getCustomerFlag())) {
                if (StringUtils.isBlank(paymentMethod)) {
                    paymentMethod = "2";//现场支付
                }
                //施工师傅直接确认，跳过客户确认付款操作
                payoutInformationMapper.updateByOrderId2(orderId, loginmanId, formatdate, formatdate, loginmanId, formatdate, paymentMethod);
                if("2".equals(paymentMethod)) {
                    //师傅现场收款成功，记录到钱包明细
                    customerRepairServiceimpl.workerOnSitePayment(orderId);
                }
            } else if ("10".equals(order.getCustomerFlag())) {
                payoutInformationMapper.updateByOrderId(orderId, loginmanId, formatdate, formatdate, loginmanId, null);
            }
            customerRepair.setCustomerFlag("3");
            message = "确认付款成功,等待施工";
        } else {
            //这里目前不会进入，因为非报修工单不会调用此接口
            //非保修
            customerRepair.setCustomerFlag("11");
            //记录确认付款时间
            //分配给财务人员确认收款-----@TODO  //目前没有做微信支付-财务分配给唯一的一位财务
//            String finance = getRandomFinanceid(loginmanId);
            String finance = getRandomFinanceid(orderId);
            if (finance == null) return ResultMsg.ARGS_ERROR.setNewErrorMsg("该公司没有财务");
            payoutInformationMapper.updateByOrderId(orderId, loginmanId, formatdate, formatdate, finance, null);
            message = "确认尾款付清成功,提交财务,待财务确认";
        }
        customerRepairServiceimpl.updateTimeAndMan(loginmanId, orderId);
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);
        //短信提醒
//        CustomerRepair order = customerRepairMapper.selectById(orderid);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单确认了到账信息，师傅即将开始施工，请您耐心等待。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(orderId);//订单名字--参数是工单号
        String content = "尊敬的用户 : 你好 ,您的" + orderType + "确认了到账信息,师傅即将开始施工,请您耐心等待 !";
        customerRepairServiceimpl.updateNotice(loginmanId, orderId, "备注", content, "0", null, null, null);
        return ResultMsg.UPDATE_SUCCESS.setNewErrorMsg(message);
    }

    private String getTheBranchIdd(String loginmanId) {
        Long deptId = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", loginmanId).select("dept_id")).getDeptId();
        String ancestors = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", deptId).select("ancestors")).getAncestors();
        String[] split = ancestors.split(",");
        String companyId = split[2];
        return companyId;
    }

    private String getTheBranchId(String loginmanId) {
        Long deptId = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", loginmanId).select("dept_id")).getDeptId();
        String ancestors = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", deptId).select("ancestors")).getAncestors();
        String[] split = ancestors.split(",");
        String companyId = split[2];
        return companyId;
    }

    /**
     * @Description 接口描述 : 施工材料上传
     * materialRepari : 工单id
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/26 17:05
     */
    @Transactional
    @Override
    public ResultMsg uploadMaterials(JSONObject jsonObject) {
        Date date = new Date();

        String materialRepari = jsonObject.getString("materialRepari"); //工单号
        if (StringUtils.isBlank(materialRepari)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("工单号不能为空");

        String loginmanId = jsonObject.getString("loginmanId");//当前登录人id
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("当前登录人id不能为空");

        String materialTime = jsonObject.getString("materialTime");
        String materialPower = jsonObject.getString("materialPower");
        String faultCondition = jsonObject.getString("faultCondition");
        String materialIllustrate = jsonObject.getString("materialIllustrate");

        /*ArrayList<String> materialAfterstring = new ArrayList<>();
        for (int i = 0; i <= split.length - 1; i++) {
            materialAfterstring.add(split[i]);
        }
        //施工后图片储存
        for (String s : materialAfterstring) {
            MaterialAfter materialAfter1 = new MaterialAfter();
            materialAfter1.setMaterialRepari(materialRepari);
            materialAfter1.setMaterialAfter(s);
            materialAfter1.setIds("555");
            materialAfterMapper.insertinsert(materialAfter1);
        }*/
        //修改订单状态
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(materialRepari);
        customerRepair.setCustomerFlag("4");

        MaterialInfo materialInfo1 = new MaterialInfo();
        materialInfo1.setMaterialRepari(materialRepari);//工单id
        materialInfo1.setMaterialIllustrate(materialIllustrate);//信息说明
        materialInfo1.setFaultCondition(faultCondition);//故障情款
        customerRepair.setSearchable("1");////把订单转到供电所
        if (EqName(materialRepari)) {//保修
//            if (StringUtils.isBlank(faultCondition)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("故障处理情况不能为空");
//            if (StringUtils.isBlank(materialPower)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("是否涉网涉点不能为空");
//            if (StringUtils.isBlank(materialIllustrate)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("发现故障不能为空");
            if ("0".equals(materialPower)) {
                //涉网涉电处理
                if (StringUtils.isBlank(jsonObject.getString("materialTime")))
                    return ResultMsg.ARGS_ERROR.setNewErrorMsg("涉网涉电的订单,恢复用电时间不能为空");
                materialInfo1.setMaterialTime(materialTime);//填入恢复点的时间
                materialInfo1.setMaterialPower(materialPower);//是否涉电涉网
            }
//            appMapper.updateMaterialInfoByOrderId(materialInfo1);
        }/* else {
//            if (StringUtils.isBlank(materialIllustrate)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("发现故障不能为空");
            //新增幂等
//            List<MaterialInfo> material_repari = materialInfoMapper.selectList(new QueryWrapper<MaterialInfo>().eq("material_repari", materialRepari));
//            if (material_repari.size() != 0) return ResultMsg.ARGS_ERROR.setNewErrorMsg("施工材料信息已经存在,请勿重复提交");
        }*/
        materialInfo1.setCreateTime(new Date());
        materialInfoMapper.insert(materialInfo1);
        String materialKey = materialInfo1.getMaterialKey();
        //施工前图片储存
        String materialBefore1 = jsonObject.getString("materialBefore");
        if (StringUtils.isNotBlank(materialBefore1)) {
            for (String s : materialBefore1.split(",")) {
                MaterialBefore materialBefore = new MaterialBefore();
                materialBefore.setMaterialRepari(materialRepari);
//                materialBefore.setIds("null");
                materialBefore.setIds(materialKey);
                materialBefore.setMaterialBefore(s);
                materialBeforeMapper.insertt(materialBefore);
            }
        }

        //施工后图片储存
        String materialAfter = jsonObject.getString("materialAfter");
        if (StringUtils.isNotBlank(materialAfter)) {
            for (String s : materialAfter.split(",")) {
                MaterialAfter materialAfter1 = new MaterialAfter();
                materialAfter1.setMaterialRepari(materialRepari);
                materialAfter1.setMaterialAfter(s);
                materialAfter1.setIds(materialKey);
                materialAfterMapper.insertinsert(materialAfter1);
            }
        }
        //记录施工时间
        customerRepair.setBuildTime(date);
        customerRepair.setCompleteTime(date);
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);//更新工单
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(materialRepari);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单施工师傅已提交了施工信息，可前往小程序进行验收和评价。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(materialRepari);//订单名字
        String content = "尊敬的用户 : 你好 ,您的" + orderType + "订单提交了施工信息,点击查看,进行评价!";
        customerRepairServiceimpl.updateNotice(loginmanId, materialRepari, "备注", content, "0", null, null, null);
        return ResultMsg.SUCCESS;
    }

    /**
     * @Description 查询工单下材料信息
     * @Author Blq <Br />
     * @Date 9:21 2022/9/14
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg selectMaterials(JSONObject jsonObject) {
        if (StringUtils.isBlank(jsonObject.getString("id"))) return ResultMsg.ARGS_ERROR;
        return ResultMsg.SELECT_SUCCESS.setNewData(appMapper.selectMaterials(jsonObject.getString("id")));
    }


    /**
     * @Description 验收评价按钮
     * @Author Blq <Br />
     * evaluationId  : 订单id
     * @Date 9:40 2022/9/14
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg==evaluationFlag=0
     **/
    @Transactional
    @Override
    public ResultMsg addEvaluation(JSONObject jsonObject) {
        String message = null;
        String formatdate = time.format(new Date());
        String evaluationId = jsonObject.getString("evaluationId");//订单号
        String loginmanId = jsonObject.getString("loginmanId"); //登录人
        String evaluationInfo = jsonObject.getString("evaluationInfo");//评价信息
        String evaluationStatus = jsonObject.getString("evaluationStatus");//评价星级
        String evaluationFlag = jsonObject.getString("evaluationFlag");//验收是否通过
        if (StringUtils.isBlank(evaluationId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("订单号不能为空");
        CustomerRepair order = customerRepairMapper.selectById(evaluationId);
        SysUser smsUser = null;
        //生成财务人员
//        String receiverBy = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>().eq("customer_key", evaluationId).select("receiver_by")).getReceiverBy();
//        String firstworker = receiverBy.split(",")[0];
//        String randomfinanceid = getRandomFinanceid(firstworker);
        //验收不通过
        CustomerRepair customerRepair = new CustomerRepair();
        if (evaluationFlag.equals("1")) {
            //删除之前备份不通过评级
            //幂等
//            List<EvaluationBackup> evaluationBackups = evaluationBackupMapper.selectList(new QueryWrapper<EvaluationBackup>()
//                    .eq("evaluation_status", evaluationInfo)//评价文字
//                    .eq("evaluation_id", evaluationId));//工单id
//            if (evaluationBackups.size() != 0) return ResultMsg.ARGS_ERROR.setNewErrorMsg("相同的订单,不通过的评价相同");
            /*EvaluationBackup evaluationBackup = new EvaluationBackup();

            //根据工单id查到之前的施工信息
//            MaterialInfo material_repari = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>().eq("material_repari", evaluationId));
            JSONObject material_repari = appMapper.selectMaterials(evaluationId);
            if (material_repari != null) {
                *//*try {
                    if (material_repari.getMaterialTime() != null)
                        evaluationBackup.setMaterialTime(time.parse(material_repari.getMaterialTime()));//恢复时间
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //保存施工信息
                BeanCopyUtils.copy(material_repari, evaluationBackup);*//*
//                String afterabutmentid = String.valueOf(id.nextId());//处理后图片对应id
//                materialAfterMapper.updateByOrderId(evaluationId, afterabutmentid);
                // 修改after表-对应处理后图片对应id
                evaluationBackup.setMaterialIllustrate(material_repari.getString("materialKey"));
                evaluationBackup.setEvaluationId(evaluationId);
//                evaluationBackup.setMaterialAfter(afterabutmentid);
                evaluationBackup.setEvaluationInfo(evaluationInfo);//评价文字信息
                evaluationBackup.setCreatTime(new Date());//创建时间
                evaluationBackup.setEvaluationStatus(evaluationStatus);//评价星级
                evaluationBackup.setEvaluationFlag(evaluationFlag);//验收是否通过
                evaluationBackupMapper.insert(evaluationBackup);
            }*/
            //执行回滚操作---直接改订单状态为待施工
            customerRepair.setCustomerKey(evaluationId);
            customerRepair.setCustomerFlag("3");
//            customerRepairMapper.updateCustomerRepairBykey(customerRepair);
            /*if (EqName(evaluationId)) {
                materialInfoMapper.updateByOrderId(evaluationId);
            } else {
                materialInfoMapper.delete(new QueryWrapper<MaterialInfo>().eq("material_repari", evaluationId));
            }*/
            //短信提醒
            if (StringUtils.isNotBlank(order.getReceiverBy())) {
                String[] rs = order.getReceiverBy().split(",");
                smsUser = sysUserMapper.selectById(rs[0]);
            }
            if (smsUser != null) {
                SendOrderMsg.sendDIY("提醒：您有一份<" + order.getCustomerHelp() + ">订单未验收通过，请尽快处理。", smsUser.getPhonenumber());
            }
        } else {
            Date date = new Date();
            //验收通过
            customerRepair.setCustomerKey(evaluationId);
            customerRepair.setCheckTime(date); //记录结束时间和验收时间
            customerRepair.setEndTime(date);
            if (!EqName(evaluationId)) {
                String randomfinanceid = getRandomFinanceid(evaluationId);
                if (StringUtils.isBlank(randomfinanceid)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("该公司没有财务");
                customerRepair.setCustomerFlag("11");
                payoutInformationMapper.updateByOrderId(evaluationId, randomfinanceid, formatdate, null, randomfinanceid, null);
                //更新公告
                String customer_key = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                        .eq("customer_key", evaluationId)).getCustomerHelp();
                String orderNote = "你的" + customer_key + "已评价,待财务确认付清尾款";
                //传入登录人.订单号,备注,更新公告信息
                customerRepairServiceimpl.updateNotice(loginmanId, evaluationId, "用户更新", orderNote, "0", null, null, null);
                //短信提醒
                smsUser = sysUserMapper.selectById(randomfinanceid);
                if (smsUser != null) {
                    SendOrderMsg.sendDIY("提醒：您有一份<" + order.getCustomerHelp() + ">订单已验收通过，请进行财务确认。", smsUser.getPhonenumber());
                }
            } else {
                //报修添加评价
                customerRepair.setCustomerFlag("7");
                //更新公告数据
                String Note = "用户更新";
                String orderNote = "你的客户报修抢修已评价,订单结束";
                //传入登录人.订单号,备注,更新公告信息
                customerRepairServiceimpl.updateNotice(loginmanId, evaluationId, Note, orderNote, "0", null, null, null);
                message = "评价成功,订单结束";
                //短信提醒
                if (StringUtils.isNotBlank(order.getCustomerPhone())) {
                    SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单已完成，感谢您的使用，祝您生活愉快。", order.getCustomerPhone(), order.getLiaisonPhone());
                }
            }

            //评论表新增幂等
            /*List<Evaluation> customer_key1 = evaluationMapper.selectList(new QueryWrapper<Evaluation>().eq("evaluation_id", evaluationId));
            if (customer_key1.size() != 0) {
                //第二次提交验收通过
                //非报修评价
                if (EqName(evaluationId)) {
                    customerRepair.setCustomerFlag("11");
                    payoutInformationMapper.updateByOrderId(evaluationId, randomfinanceid, formatdate, null, randomfinanceid);
                    //更新公告
                    String customer_key = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                            .eq("customer_key", evaluationId)).getCustomerHelp();
                    String orderNote = "你的" + customer_key + "已评价,待财务确认付清尾款";
                    //传入登录人.订单号,备注,更新公告信息
                    customerRepairServiceimpl.updateNotice(loginmanId, evaluationId, "用户更新", orderNote, "0", null, null, null);

                } else {
                    //报修添加评价
                    customerRepair.setCustomerFlag("7");
                    //更新公告数据
                    String Note = "用户更新";
                    String orderNote = "你的客户报修抢修已评价,订单结束";
                    //传入登录人.订单号,备注,更新公告信息
                    customerRepairServiceimpl.updateNotice(loginmanId, evaluationId, Note, orderNote, "0", null, null, null);
                    message = "评价成功,订单结束";
                }
            } else {//首次提交

                //非报修评价
                if (EqName(evaluationId)) {
                    customerRepair.setCustomerFlag("11");
                    jsonObject.put("evaluationKey", id.nextId());
                    appMapper.addEvaluation(jsonObject);
                    payoutInformationMapper.updateByOrderId(evaluationId, randomfinanceid, formatdate, null, randomfinanceid);
                    //更新公告
                    String customer_key = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                            .eq("customer_key", evaluationId)).getCustomerHelp();
                    String orderNote = "你的" + customer_key + "已评价,待财务确认付清尾款";
                    //传入登录人.订单号,备注,更新公告信息
                    customerRepairServiceimpl.updateNotice(loginmanId, evaluationId, "用户更新", orderNote, "0", null, null, null);
                    message = "评价成功,待财务人员确认付清尾款";
                } else {
                    //报修添加评价
                    customerRepair.setCustomerFlag("7");
                    jsonObject.put("evaluationKey", id.nextId());
                    appMapper.addEvaluation(jsonObject);

                    //更新公告数据
                    String Note = "用户更新";
                    String orderNote = "你的客户报修抢修已评价,订单结束";
                    //传入登录人.订单号,备注,更新公告信息
                    customerRepairServiceimpl.updateNotice(loginmanId, evaluationId, Note, orderNote, "0", null, null, null);
                    message = "评价成功,订单结束";
                }
            }*/
        }
        EvaluationBackup evaluationBackup = new EvaluationBackup();

        JSONObject material_repari = appMapper.selectMaterials(evaluationId);
        if (material_repari != null) {
            evaluationBackup.setMaterialIllustrate(material_repari.getString("materialKey"));
            evaluationBackup.setEvaluationId(evaluationId);
            evaluationBackup.setEvaluationInfo(evaluationInfo);//评价文字信息
            evaluationBackup.setCreatTime(new Date());//创建时间
            evaluationBackup.setEvaluationStatus(evaluationStatus);//评价星级
            evaluationBackup.setEvaluationFlag(evaluationFlag);//验收是否通过
            evaluationBackupMapper.insert(evaluationBackup);
        }
        customerRepairMapper.updateCustomerRepairBykey(customerRepair);
        // 结算订单
        customerRepairServiceimpl.payoffOrder(evaluationId);
        return ResultMsg.SUCCESS.setNewErrorMsg(message);
    }

    private String getRandomFinanceid(String orderId) {
        List<PayoutInformation> list = payoutInformationMapper.selectList(new QueryWrapper<PayoutInformation>().eq("customer_key", orderId));
        String deptId = null;
        if (list.size() > 0) {
            deptId = list.get(0).getPayoutFromId();
        }
        if (deptId != null) {
            List<SysUser> users = sysUserMapper.selectWorkerByDept(deptId, "finance");
            if (users.size() > 0) {
                return users.get(0).getUserId().toString();
            }
        }
        /*CustomerRepair order = customerRepairMapper.selectById(orderId);
        String customerAddress = order.getCustomerAddress();
        //1628618911551913985是《云南建源电力工程有限公司》的ID，目前业务需求是该公司财务确认
        List<SysUser> users = sysUserMapper.selectWorkerByDept("1628618911551913985", "finance");*/
        /*if (users.size() > 0) {
            for (SysUser user : users) {
                if (customerAddress.contains(user.getDept().getCity().substring(0,2))){
                    return user.getUserId().toString();
                }
            }
            return users.get(0).getUserId().toString();
        }*/
        return null;
    }
    //根据员工id 获取公司随机财务id
    private String getRandomFinanceidOld( String loginmanId) {
        //evaluationId-订单号
        //loginmanId---登录评价用户id
        //查到该公司财务id
        //根据部门id 去查财务人员
        String num = "1614143480190832642";//1614143480190832642
        List<SysUserPost> sysUserPosts = sysUserPostMapper.selectList(new QueryWrapper<SysUserPost>().eq("post_id", num).select("user_id"));
        //公司id
        String receiverBy = String.valueOf(getOrgId(loginmanId));
        ArrayList<String> strings = new ArrayList<>();
        for (SysUserPost sysUserPost : sysUserPosts) {//公司id比对
            //登录人的--财务人员的公司id和工人公司id一样-getTheBranchId
            Long aLong1 = getOrgId(String.valueOf(sysUserPost.getUserId()));//根据员工id获取公司id
            if (receiverBy.equals(String.valueOf(aLong1))) strings.add(String.valueOf(sysUserPost.getUserId()));
        }
        //生成随机的财务id
        if (strings.size() != 0) {
            Random random = new Random();
            int i = random.nextInt(strings.size());
            String randomfinanceid = strings.get(i);
            return randomfinanceid;
        }
        return null;
    }

    /**
     * @Description 接口描述 :
     * 传入一个订单号判断是否是非保修订单
     * TRUE : 报修订单
     * FALSE : 非保修订单
     */
    public boolean EqName(String evaluationId) {
        return customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                .eq("customer_key", evaluationId)).getCustomerHelp().equals("客户报修抢修");
    }

    /**
     * @Description 最终财务确认
     * @Author Blq <Br />
     * @Date 10:02 2022/9/14
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Transactional
    @Override
    public ResultMsg finalFinancialConfirmation(JSONObject jsonObject) {
        String date = time.format(new Date());//时间
        String mesage = null;
        //登录人id
        String loginmanId = jsonObject.getString("loginmanId");
        if (loginmanId == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("登录人id不能为空");
        //工单id
        String orderid = jsonObject.getString("customer_key");
        if (orderid == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("工单id不能为空");
        //到账凭证
        String confirmProof = jsonObject.getString("confirmProof");
        if (confirmProof == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("到账凭证不能为空");

        UpdateWrapper<CustomerRepair> wrapper = new UpdateWrapper<>();
        wrapper.eq("customer_key", orderid);
        wrapper.set("complete_time", date);
        wrapper.set("end_time", date);
        wrapper.set("customer_flag", "7");
        wrapper.set("Closing_by", loginmanId);
        wrapper.set("Close_note", "订单完成");
        boolean update = customerRepairServiceimpl.update(wrapper);
        if (update != true) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("修改订单信息失败");
        //支付订单表
        payoutInformationMapper.updateByOrderId(orderid, loginmanId, date, date, loginmanId, confirmProof);
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(orderid);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单已完成，感谢您的使用，祝您生活愉快。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(orderid);//订单名字--参数是工单号
        String content = "你的" + orderType + "财务确认成功,订单结束!";
        String remark = "备注";
        //传入登录人id ,工单id.备注.公告内容
        customerRepairServiceimpl.updateNotice(loginmanId, orderid, remark, content, "0", null, null, null);
        return ResultMsg.UPDATE_SUCCESS.setNewErrorMsg("确认成功,订单完成");
    }

    /**
     * @Description 忘记密码
     * @Author Blq <Br />
     * @Date 10:44 2022/9/17
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg forgetPassword(JSONObject jsonObject) {
        JSONObject info = appMapper.getUserInfoByUserName(jsonObject.getString("userName"));
        if (info == null) return ResultMsg.OBJECT_ERROR.setNewErrorMsg("查无此信息");
        info.put("userPassword", jsonObject.getString("userPassword"));
        appMapper.updateUser(info);
        return ResultMsg.UPDATE_SUCCESS;
    }

    /**
     * @Author: xiaw
     * web端调派订单接口
     */
    @Override
    public ResultMsg firm(JSONObject jsonObject) {
        List<JSONObject> firm = appMapper.firm(jsonObject);
        return ResultMsg.SUCCESS.setNewData(firm);
    }

    @Override
    public ResultMsg editCuotomer(JSONObject jsonObject) {
        JSONObject user = appMapper.getUserSysById(jsonObject.getString("user"));
        boolean name = Pattern.matches("/^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\\d{8})$/", user.getString("user_name"));
        if (!name) {
            return ResultMsg.ENTIY_ERROR;
        }
        JSONObject info = appMapper.getUserInfoByUserName(user.getString("user_name"));
        if (info == null) {
            return ResultMsg.ENTIY_ERROR;
        }
        JSONObject customer = appMapper.getTicketById(jsonObject.getString("customer"));
        customer.put("customerPlayer", info.getString("userId"));
        appMapper.updaTeticketByOrderId(null);
        return ResultMsg.SUCCESS;
    }

    /**
     * @Description 接口描述 : 根据订单号获取到服务人员的信息
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/30 10:21
     */
    @Override
    public ResultMsg userInfoSys(String customerKey) {
        LinkedHashSet<Long> longs = new LinkedHashSet<>();
        //根据订单号去查用户
        String customer_key = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>().eq("customer_key", customerKey)).getReceiverBy();
        String[] split = customer_key.split(",");
        for (String s : split) {
            longs.add(Long.parseLong(s));
        }
        Ticket ticket_repair1 = ticketMapper.selectOne(new QueryWrapper<Ticket>().eq("ticket_repair", customerKey));
        if (ticket_repair1 != null) {
            String ticket_repair = ticket_repair1.getTicketUser();
            String[] split1 = ticket_repair.split(",");
            for (String s2 : split1) {
                longs.add(Long.parseLong(s2));
            }
        }
        ArrayList<SysUser> sysUsers = new ArrayList<>();
        for (Long aLong : longs) {
            sysUsers.add(sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("user_id", aLong)));
        }
        return ResultMsg.SUCCESS.setNewData(sysUsers);
    }

    @Override
    public R finance(String id) {
        if (StringUtils.isBlank(id)) return R.fail();
        // TODO 查询收款信息
        PayoutInformation customer_key = payoutInformationMapper.selectOne(new QueryWrapper<PayoutInformation>().eq("customer_key", id));
        return R.ok(customer_key);
    }

    @Override
    public ResultMsg serveClassify() {
        return ResultMsg.SUCCESS.setNewData(appMapper.serveClassify());
    }

    /**
     * @Description 接口描述 : 工单池展示接口
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 0:04
     */
    @Override
    public ResultMsg orderPoollist() {
        List<CustomerRepair> list = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>()
                .eq("customer_flag", "99"));
        return ResultMsg.SUCCESS.setNewData(list);
    }

    /**
     * @Description 接口描述 : 转单接口--把订单转移到订单池
     * @Params * @param null
     * customer_key : 订单id
     * loginmanId  : 当前登录人id
     * @Return
     * @Author xiaw
     * @Date 2022/12/25 0:15
     */
    @Override
    public ResultMsg transfer(JSONObject jsonObject) {
        if (StringUtils.isBlank(jsonObject.getString("customer_key"))) return ResultMsg.ARGS_ERROR;
        if (StringUtils.isBlank(jsonObject.getString("loginmanId"))) return ResultMsg.ARGS_ERROR;
        //获得订单主键
        String customer_key = jsonObject.getString("customer_key");
        //当前登录人
        String updateman = jsonObject.getString("loginmanId");

        //根据订单号去查申请信息.如果就就拒绝转单

        Date date = new Date();
        UpdateWrapper<CustomerRepair> wrapper = new UpdateWrapper<>();
        wrapper.eq("customer_key", customer_key);
        wrapper.set("customer_flag", "99");
        wrapper.set("customer_unit", updateman);//转单人id
        wrapper.set("customer_time", date);//转单时间
        wrapper.set("company_id", null);
        wrapper.set("update_time", date);
        wrapper.set("receiver_by", null);
        wrapper.set("receiver_man",null);
        wrapper.set("receive_time",null);
        //记录转单记录--记录更新人个更新时间
        customerRepairServiceimpl.updateTimeAndMan(updateman, customer_key);
        customerRepairServiceimpl.update(wrapper);
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(customer_key);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单转到了订单池，等待空闲师傅的接单，请耐心等待。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        // 短信提醒
        poolSendWorker(order);
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(customer_key);//订单名字--参数是工单号
        String content = "你的" + orderType + "订单转到订单池,点击查看详情!";
        //传入登录人id ,工单id.备注.公告内容
        customerRepairServiceimpl.updateNotice(updateman, customer_key, "备注", content, "0", null, null, null);
        return ResultMsg.SUCCESS.setNewErrorMsg("订单转到订单池成功");
    }

    /**
     * 工单池抢单接口----需要工人id和订单id
     *
     * @param jsonObject
     * @return
     */
    @Override
    public ResultMsg snatchOrders(JSONObject jsonObject) {
        //当前登录人id
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR;
        //订单id
        String customerKey = jsonObject.getString("customerKey");
        if (StringUtils.isBlank(customerKey)) return ResultMsg.ARGS_ERROR;

        //获取公司id
        Long aLong = getOrgId(loginmanId);

        //查询订单是否已经关闭
        Date date = new Date();
        boolean b = whetherTheOrderIsClosedOrNot(customerKey);
        if (b) return ResultMsg.SELECT_SUCCESS.setNewErrorMsg("该订单已经关闭,抢单失败");
        //判断报修和非保修
        boolean update = false;
        boolean b2 = EqName(customerKey);
        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setCustomerKey(customerKey);
        customerRepair.setReceiveTime(date);
        customerRepair.setUpdateBy(loginmanId);
        customerRepair.setUpdateTime(date);
        customerRepair.setCompanyId(String.valueOf(aLong));

        lock.lock();
        try {
            if (b2) {//报修订单
                customerRepair.setCustomerFlag("21");
                customerRepair.setReceiverMan(loginmanId);
            } else {//非保修订单
                customerRepair.setReceiverMan(loginmanId);
                customerRepair.setCustomerFlag("1");
            }
            customerRepair.setReceiverBy(loginmanId);
            customerRepairMapper.updateCustomerRepairBykey(customerRepair);
        } finally {
            lock.unlock();
        }
        //更新公告
//        String userName = getUserName(loginmanId);
        SysUser smsUser = sysUserMapper.selectById(loginmanId);
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(customerKey);
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单被<" + smsUser.getNickName() + ">[" + smsUser.getPhonenumber() + "]师傅接单，接下来由他完成您的订单。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(customerKey);//订单名字--参数是工单号
        String content = "你的" + orderType + "订单被" + smsUser.getNickName() + "师傅抢到,接下来由他为你完成订单!";
        //传入登录人id ,工单id.备注.公告内容
        customerRepairServiceimpl.updateNotice(loginmanId, customerKey, "备注", content, "0", null, null, null);
        return ResultMsg.SELECT_SUCCESS.setNewErrorMsg("抢单成功");
    }

    //判断订单是否已经关闭
    public boolean whetherTheOrderIsClosedOrNot(String customerKey) {
        boolean customer_key = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>().eq("customer_key", customerKey)).getCustomerFlag().equals("7");
        return customer_key;
    }

    /**
     * @Description 接口描述 : 员工关闭工单接口
     * 传入
     * 用户id
     * 订单id
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/26 9:39
     */
    @Override
    public ResultMsg close(JSONObject jsonObject) {
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR;
        String customerKey = jsonObject.getString("customerKey");
        if (StringUtils.isBlank(customerKey)) return ResultMsg.ARGS_ERROR;
        String CloseNote = jsonObject.getString("CloseNote");

        //判端是否是工单不是客户产权的关闭订单行为-->反馈信息给所属供电所
        String mannerOfWriting = jsonObject.getString("styleOrMannerOfWriting");
        if (mannerOfWriting.equals("1")) {
            CustomerRepair customerRepair = new CustomerRepair();
            customerRepair.setSearchable("1");//反馈信息给供电所
            customerRepair.setCustomerKey(customerKey);
            customerRepair.setUpdateBy(loginmanId);
            customerRepair.setUpdateTime(new Date());
            customerRepairMapper.updateCustomerRepairBykey(customerRepair);
        }

        //记录操作人和时间
        customerRepairServiceimpl.updateTimeAndMan(loginmanId, customerKey);
        //根据id修改信息
        UpdateWrapper<CustomerRepair> wrapper = new UpdateWrapper<>();
        wrapper.eq("customer_key", customerKey);
        wrapper.set("Closing_time", new Date());//关闭订单时间
        wrapper.set("Closing_by", loginmanId);//关闭订单人
        wrapper.set("Close_note", CloseNote);//关闭订单备注
        wrapper.set("customer_flag", "77");
        boolean update = customerRepairServiceimpl.update(wrapper);
        if (update) {
            CustomerRepair order = customerRepairMapper.selectById(customerKey);
            //记录公告
            String remak = "用户";
            String content;
            if (mannerOfWriting.equals("1")) {
                content = "您的<" + order.getCustomerHelp() + ">订单已关闭，原因：订单涉及设备不是您的产权！订单已反馈到供电所处理。";
            } else {
                content = "您的<" + order.getCustomerHelp() + ">订单已关闭，原因：" + CloseNote;
            }
            //短信提醒
            if (StringUtils.isNotBlank(order.getCustomerPhone())) {
                SendOrderMsg.sendDIY("尊敬的用户您好，" + content, order.getCustomerPhone(), order.getLiaisonPhone());
            }
            //传入登录人.订单号,备注,更新公告信息
            customerRepairServiceimpl.updateNotice(loginmanId, customerKey, remak, content, "0", null, null, null);
            return ResultMsg.SELECT_SUCCESS.setNewErrorMsg("订单关闭成功");
        }
        return ResultMsg.ARGS_ERROR.setNewErrorMsg("订单关闭失败");
    }

    /**
     * @Descriptio 搜索框高级查询
     * @Author Blq <Br />
     * @Date 14:58 2022/10/14
     * @Param jsonObject
     * @Return com.blq.common.utils.ResultMsg
     **/
    @Override
    public ResultMsg advancedQuery(JSONObject jsonObject) {
        //根据传入的用户名以及手机号去查询订单信息
        String userphone = jsonObject.getString("userphone");
        String username = jsonObject.getString("username");
        if (userphone.isEmpty() && username.isEmpty()) return ResultMsg.ARGS_ERROR.setNewErrorMsg("参数不能为空");
        QueryWrapper<CustomerRepair> customerRepairQueryWrapper = new QueryWrapper<>();
        customerRepairQueryWrapper.like("customer_phone", userphone);
        customerRepairQueryWrapper.like("customer_name", username);
        CustomerRepair customerRepair = customerRepairMapper.selectOne(customerRepairQueryWrapper);
        return ResultMsg.SELECT_SUCCESS.setNewData(customerRepair);
    }

    /**
     * @Description 接口描述 : 指派订单接口
     * "customerKey": "1056929541244583936",
     * "loginmanId": "1023995635902185472",
     * 指派人员id :
     * customerPlayer : 指派工人的id--指派给谁
     * "orderStatus": "1"
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/28 17:05
     */
    @Transactional
    @Override
    public ResultMsg designate(JSONObject jsonObject) {
        //数据准备
        Date date = new Date();
        String customerKey = jsonObject.getString("customerKey");
        String loginmanId = jsonObject.getString("loginmanId");//指派人id
        String customerPlayer = jsonObject.getString("customerPlayer");
        String companyId = jsonObject.getString("companyId");
        //判断
        if (StringUtils.isBlank(customerKey)) return ResultMsg.ARGS_ERROR;
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR;
        if (StringUtils.isBlank(customerPlayer)) return ResultMsg.ARGS_ERROR;//工人
        if (StringUtils.isBlank(companyId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("公司id不能为空");//工人

        CustomerRepair customerRepair = new CustomerRepair();
        customerRepair.setUpdateTime(date);
        customerRepair.setUpdateBy(loginmanId);
        customerRepair.setCustomerFlag("0");
//        customerRepair.setReceiveTime(new Date());
        customerRepair.setCustomerDesignate(loginmanId);
        customerRepair.setCustomerDesignateTime(date);
        customerRepair.setCompanyId(companyId);
        customerRepair.setCustomerKey(customerKey);
        customerRepair.setReceiverBy(customerPlayer);
        customerRepair.setReceiverMan(customerPlayer);

        customerRepairMapper.updateCustomerRepairBykey(customerRepair);
        //短信提醒
        CustomerRepair order = customerRepairMapper.selectById(customerKey);
        SysUser smsUser = sysUserMapper.selectById(customerPlayer);
        SendOrderMsg.sendDIY("提醒：您有一份<" + order.getCustomerHelp() + ">订单被指派，请尽快处理。", smsUser.getPhonenumber());
        if (StringUtils.isNotBlank(order.getCustomerPhone())) {
            SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单被指派给了<" + smsUser.getNickName() + ">[" + smsUser.getPhonenumber() + "]师傅接单，接下来由他完成您的订单。", order.getCustomerPhone(), order.getLiaisonPhone());
        }
        //更新公告信息
        String orderType = customerRepairServiceimpl.maintenanceType(customerKey);//订单名字--参数是工单号
        String content = "你的" + orderType + "被指派给了" + getUserName(customerPlayer) + "师傅,点击订单查看详情!";
        customerRepairServiceimpl.updateNotice(loginmanId, customerKey, "备注", content, "0", null, null, null);
        return ResultMsg.SUCCESS.setNewErrorMsg("指派订单成功");
    }

    /**
     * @Description 接口描述 : 各种提交按钮
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2022/12/30 11:14
     */
    @Transactional
    @Override
    public ResultMsg submit(JSONObject jsonObject) {
        //订单号
        String customerKey = jsonObject.getString("customerKey");
        String loginmanId = jsonObject.getString("ticketReviewer");

        ResultMsg<Object> objectResultMsg = new ResultMsg<>();
        //提交审核资料
        String auditor = null;
        if (jsonObject.getString("orderStatus").equals("8")) {
            try {
                objectResultMsg = ticketReview(jsonObject);
            } catch (Exception e) {
                log.error("error is {}", e);
                return ResultMsg.ARGS_ERROR.setNewErrorMsg("提交审核资料失败,执行回滚");
            }
        }
        //审核通过
        if (jsonObject.getString("orderStatus").equals("9")) {
            try {
                objectResultMsg = approveRequest(jsonObject);
            } catch (Exception e) {
                log.error("error is {}", e);
                return ResultMsg.ARGS_ERROR.setNewErrorMsg("审核通过失败,执行回滚");
            }
        }
        //填写勘察资料失败
        if (jsonObject.getString("orderStatus").equals("1")) {
            try {
                objectResultMsg = addInvestigation(jsonObject);
            } catch (Exception e) {
                log.error("error is {}", e);
//                log.info("填写勘察资料失败,执行回滚");
                return ResultMsg.ARGS_ERROR.setNewErrorMsg("填写勘察资料失败,执行回滚");
            }
        }
        return objectResultMsg;
    }

    /**
     * @Description 接口描述 :  发现页接口
     * @Params * @param null 传入用户id
     * @Return
     * @Author xiaw
     * @Date 2023/1/2 22:01
     */
    @Override
    public ResultMsg find(JSONObject jsonObject) {
        //登录人id
        String userId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(userId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户id不能为空");
        List<SysNotice> sysNotices = sysNoticeMapper.selectNoticeByUserId(userId);
        return ResultMsg.SUCCESS.setNewData(sysNotices);
    }

    public ResultMsg findOld(JSONObject jsonObject) {
        //登录人id
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户id不能为空");
        //公司id
        Long aLong = getOrgId(loginmanId);
        LinkedHashSet<SysNotice> sysNotices = new LinkedHashSet<>();
        //根据用户id去查他的未完成订单
        List<SysNotice> sysNotices1 = sysNoticeMapper.selectList(new QueryWrapper<SysNotice>()
                .eq("status", "0").eq("customer_key", "1").orderByDesc("update_time"));
        sysNotices1.forEach(a -> sysNotices.add(a));
        //私人的
        //根据用户去查用户的订单号
        List<CustomerRepair> list = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>().eq("customer_id", loginmanId).orderByDesc("create_time"));
        List<SysNotice> sysNotices2 = null;
        if (list.size() != 0) {
            for (CustomerRepair customerRepair : list) {
                sysNotices2 = sysNoticeMapper.selectList(new QueryWrapper<SysNotice>().eq("status", "0")
                        .eq("customer_key", customerRepair.getCustomerKey())
                        .orderByDesc("update_time"));
            }
            for (SysNotice sysNotice : sysNotices2) {
                sysNotice.setReadNoWorker("1");
                sysNotice.setReadNoAudit("1");
                sysNotice.setReadNoFinance("1");
            }
            if (sysNotices2.size() != 0) {
                sysNotices2.forEach(a -> sysNotices.add(a));
            }
        }
        //根据登录人id去分辨是用户还是
        String userFlag = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", loginmanId).select("user_flag")).getUserFlag();

        ArrayList<String> strings = roleJudgment(loginmanId);
        for (String string : strings) {
            if (string.equals("分公司施工人员") && userFlag.equals("1")){
                List<SysNotice> list1 = sysNoticeMapper.selectByloginmanId(loginmanId,aLong);
                if (list1.size() != 0) {
                    for (SysNotice sysNotice : list1) {
                        sysNotice.setReadNoAudit("1");
                        sysNotice.setReadNoFinance("1");
                        sysNotice.setReadNo("1");
                        sysNotices.add(sysNotice);
                    }
                }
            }
            if (string.equals("分公司财务")&& userFlag.equals("1")){

            }
            if (string.equals("分公司运维部门负责人")&& userFlag.equals("1")){
                List<SysNotice> list1 =  sysNoticeMapper.selectByloginmanIdAudit(loginmanId,aLong);

                if (list1.size() != 0) {
                    for (SysNotice sysNotice : list1) {
                        sysNotice.setReadNoAudit("1");
                        sysNotice.setReadNoWorker("1");
                        sysNotice.setReadNo("1");
                        sysNotices.add(sysNotice);
                    }
                }
            }

        }

        return ResultMsg.SUCCESS.setNewData(sysNotices);
    }

    /**
     * @Description 接口描述 : 财务确认到账接口（弃用）
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2023/1/3 9:52
     * 传入 ;
     * 当前登录人id
     * 工单号
     * 查找工单审核信息->得到部门id->
     */
    @Override
    public ResultMsg acknowledgement(JSONObject jsonObject) {
        //登录人id
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("用户id不能为空");
        String customer_key = jsonObject.getString("customerKey");
        if (StringUtils.isBlank(customer_key)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("订到号不能为空");

        //根据登录人id去分辨是用户还是
        String userFlag = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", loginmanId).select("user_flag")).getUserFlag();
        //该订单的人所属部门
        ArrayList<String> strings = roleJudgment(loginmanId);
        for (String string : strings) {
            if (string.equals("分公司财务")&& userFlag.equals("1")) {
                String companyId = customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                        .eq("customer_key", customer_key).select("company_id")).getCompanyId();
                if (getTheBranchIdd(loginmanId).equals(companyId)) {
                    UpdateWrapper<CustomerRepair> wrapper = new UpdateWrapper<>();
                    wrapper.eq("customer_key", customer_key);
                    wrapper.set("customer_flag", "7");
                    String date = time.format(new Date());
                    wrapper.set("end_time", date);
                    boolean update = customerRepairServiceimpl.update(wrapper);
                    UpdateWrapper<PayoutInformation> queryWrapper = new UpdateWrapper<>();
                    queryWrapper.eq("customer_key", customer_key);
                    queryWrapper.set("confirmation_payment_time", date);
                    queryWrapper.set("confirmation_payment_by", loginmanId);
                    queryWrapper.set("confirm_the_recipient", loginmanId);
                    queryWrapper.set("confirm_the_time_of_payment", date);//确认到账时间
                    payoutInformationService.update(queryWrapper);
                    //短信提醒
                    CustomerRepair order = customerRepairMapper.selectById(customer_key);
                    if (StringUtils.isNotBlank(order.getCustomerPhone())) {
                        SendOrderMsg.sendDIY("尊敬的用户您好，您的<" + order.getCustomerHelp() + ">订单已完成，感谢您的使用，祝您生活愉快。", order.getCustomerPhone(), order.getLiaisonPhone());
                    }
                    String node = "你的订单,财务确认到账成功! 结束";
                    String remark = "财务";
                    customerRepairServiceimpl.updateNotice(loginmanId, customer_key, remark, node, "0", null, null, null);
                    return ResultMsg.SUCCESS.setNewErrorMsg(node);
                }
            }
        }
        return ResultMsg.ARGS_ERROR.setNewErrorMsg("你不是财务人员");

    }


    //遍历List<CustomerRepair> .填充ArrayList<SysNotice> sysNotices
    public ArrayList<SysNotice> fillInTheBlanks(ArrayList<SysNotice> sysNotices, List<CustomerRepair> list) {
        list.forEach(a -> sysNotices.add(sysNoticeMapper
                .selectOne(new QueryWrapper<SysNotice>()
                        .orderByDesc("update_time")
                        .eq("customer_key", a.getCustomerKey()))));
        return sysNotices;
    }

    /**
     * @Description 接口描述 : 查看用户的所有订单
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2023/1/6 15:44
     */
    @Override
    public ResultMsg viewAllUserOrders(JSONObject jsonObject) {
        //用户的
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人员不能为空");
        //查询待处理订单
        //判断员工的部门查看信息权限
        Long deptId = sysUserMapper.selectOne(new QueryWrapper<SysUser>()
                .eq("user_id", loginmanId)//登录人id
                .select("dept_id")).getDeptId();
        if (deptId == 1614831143398977538L || deptId == 1614830547224801281L) {
            if (deptId == 1614831143398977538L) return ResultMsg.ARGS_ERROR.setNewErrorMsg("你的个人信息没有填写完整,无法查看订单");
            if (deptId == 1614830547224801281L) return ResultMsg.ARGS_ERROR.setNewErrorMsg("你未分配部门,无权查看订单");

        } else {
            //用户查看所有的订单
            LinkedHashSet<CustomerRepair> customerRepairs = new LinkedHashSet<>();
            List<CustomerRepair> list = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>()
                    .eq("customer_id", loginmanId)
                    .orderByDesc("create_time"));
            list.forEach(a -> customerRepairs.add(a));
            //查公司id
            Long alongdanwei = getOrgId(loginmanId);
            //审核人的
            QueryWrapper<Ticket> ticketQueryWrapper1 = new QueryWrapper<>();
            ticketQueryWrapper1.eq("ticket_reviewer", loginmanId);
            ticketQueryWrapper1.eq("ticket_reslover", "2");
            List<Ticket> tickets1 = ticketMapper.selectList(ticketQueryWrapper1);
            for (Ticket ticket : tickets1) {
                customerRepairs.add(customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                        .eq("customer_key", ticket.getTicketRepair())
                        .eq("company_id", alongdanwei)
                        .orderByDesc("create_time")));
            }
            //师傅的
            List<CustomerRepair> list1 = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>()
                    .like("receiver_by", loginmanId).orderByDesc("create_time"));
            list1.forEach(a -> customerRepairs.add(a));
            QueryWrapper<Ticket> ticketQueryWrapper2 = new QueryWrapper<>();
            ticketQueryWrapper2.like("ticket_user", loginmanId);
            List<Ticket> tickets2 = ticketMapper.selectList(ticketQueryWrapper1);
            for (Ticket ticket : tickets2) {
                customerRepairs.add(customerRepairMapper.selectOne(new QueryWrapper<CustomerRepair>()
                        .eq("customer_key", ticket.getTicketRepair())
                        .eq("company_id", alongdanwei)
                        .orderByDesc("create_time")));
            }
            return ResultMsg.SUCCESS.setNewData(customerRepairs);
        }
        return ResultMsg.ARGS_ERROR.setNewErrorMsg("发生了未知故障 !");
    }

    /**
     * @Description 接口描述 :
     * @Params * @param null
     * @Return 查询所用用户的接口
     * @Author xiaw
     * @Date 2023/1/17 9:19
     */
    @Override
    public ResultMsg queryUser() {
        List<SysUser> sysUsers = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                .eq("dept_id", 1613808083627782145L)//用户部门id
                .eq("status", "0")
                .eq("del_flag", "0"));
        //用户地址
        for (SysUser user : sysUsers) {
            UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", user.getUserId()).select("user_address"));
            user.setUserAddress(userInfo.getUserAddress());
        }
        return ResultMsg.SUCCESS.setNewData(sysUsers);
    }

    /**
     * @Description 接口描述 :
     * @Params * @param null
     * @Return 查询该公司所有员工
     * @Author xiaw
     * @Date 2023/1/17 11:45
     */
    @Override
    public ResultMsg enquiringWorker(Long deptId) {
//        查询该公司所有员工--不包括未分配的员工--用户部门--1613808083627782145  未分部门--1614830547224801281
        if (!deptId.equals(1614831143398977538L) && !deptId.equals(1613808083627782145L) && !deptId.equals(1614830547224801281L)) {
            //查到
            List<SysDept> ancestors = sysDeptMapper.selectDeptList(new QueryWrapper<SysDept>().eq("dept_id", deptId));
            SysDept sysDept = ancestors.get(0);
            String[] split = sysDept.getAncestors().split(",");
            //公司id
            String number = split[2];
            //查询该所有员工
            List<SysUser> sysUserList = sysUserMapper.getCompanyId(number);
            return ResultMsg.SUCCESS.setNewData(sysUserList);
        }
        return ResultMsg.SUCCESS.setNewErrorMsg("该部门不需要负责人");
    }

    /**
     * @Description 接口描述 : 供电所查该供电所顶单--checkAnOrder
     * @Params * @param null
     * @Return---根据公司id 以及订单可查状态查看
     * @Author xiaw
     * `searchable` varchar(255) DEFAULT NULL COMMENT '供电所可查 : 1 可查    /   0.不可查     /2.
     * @Date 2023/1/6 15:44
     */
    @Override
    public ResultMsg checkAnOrder(@RequestBody JSONObject jsonObject) {
        String loginmanId = jsonObject.getString("loginmanId");
        if (StringUtils.isBlank(loginmanId)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人id不能为空");
        String searchable = jsonObject.getString("searchable");
        if (StringUtils.isBlank(searchable)) return ResultMsg.ARGS_ERROR.setNewErrorMsg("登录人id不能为空");

        //获取公司id
        Long aLong = getOrgId(loginmanId);
        QueryWrapper<CustomerRepair> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", aLong);
        wrapper.eq("searchable", searchable);
        List<CustomerRepair> list = customerRepairMapper.selectList(wrapper);
        return ResultMsg.SUCCESS.setNewData(list);
    }

    /**
     * @Description 接口描述 :查所有的财务人员 -checkFinancialAffairs
     * @Params * @param null
     * @Return
     * @Author xiaw
     * @Date 2023/1/6 15:44
     */
    @Override
    public R checkFinancialAffairs(@RequestBody JSONObject jsonObject) {
        //传入一个公司id
        String customerUnit = jsonObject.getString("customerUnit");
        if (StringUtils.isBlank(customerUnit)) return R.fail("部门id不能为空");
        //传入一个公司id,查单该公司的所有财务人员的ids
//        ArrayList<Long> strings = getLongs(customerUnit);
        List<Long> strings = new ArrayList<>();
        //1628618911551913985是《云南建源电力工程有限公司》的ID，目前业务需求是该公司财务确认
//        List<SysUser> users = sysUserMapper.selectWorkerByDept("1628618911551913985", "finance");
        List<SysUser> users = sysUserMapper.selectWorkerByDept(customerUnit, "finance");
        if (users.size() > 0) {
            for (SysUser user : users) {
                strings.add(user.getUserId());
            }
        }
        return R.ok(strings);
    }

    //传入一个公司id,查单该公司的所有ids
    @NotNull
    private ArrayList<Long> getLongs(String customerUnit) {
        String num = "1614143480190832642";//1614143480190832642 //财务部门写死角色id.......
        //所有的财务id
        QueryWrapper<SysUserPost> sysUserPostQueryWrapper = new QueryWrapper<>();
        sysUserPostQueryWrapper.eq("post_id", num);
        sysUserPostQueryWrapper.select("user_id");
        List<SysUserPost> sysUserPosts = sysUserPostMapper.selectList(sysUserPostQueryWrapper);

        ArrayList<Long> strings = new ArrayList<>();
        for (SysUserPost sysUserPost : sysUserPosts) {
            Long userId = sysUserPost.getUserId();
            QueryWrapper<SysUser> select = new QueryWrapper<SysUser>().eq("user_id", userId).select("dept_id");
            Long deptId = sysUserMapper.selectOne(select).getDeptId();
            //根据部门id查次顶级部门
            String dept_id = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", String.valueOf(deptId))).getAncestors();
            String[] split1 = dept_id.split(",");
            //得到次顶级部门id
            String s = split1[2];
            Long deptId1 = sysDeptMapper.selectOne(new QueryWrapper<SysDept>().eq("dept_id", s)).getDeptId();
            if (Long.parseLong(customerUnit) == deptId1) {
                strings.add(userId);
            }
        }
        return strings;
    }

    /**
     * @Description 接口描述 :
     * @Params * @param null
     * @Return 查询各类订单--小程序和app端都要
     * @Author xiaw
     * @Date 2023/1/31 14:43
     */
    @Override
    public R queryVariousOrders(JSONObject jsonObject) {
        String loginmanId = jsonObject.getString("loginmanId");
        LinkedHashSet<CustomerRepair> customerRepairsList = new LinkedHashSet<>();//去重集合

        //获取师傅的公司id
        Long aLong = getOrgId(loginmanId);
        //公开公告
        Integer announcement = new Integer(0);

        //根据登录人id去分辨是用户还是
        String userFlag = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", loginmanId).select("user_flag")).getUserFlag();

        HashMap<String, Integer> map = new HashMap<>();
        ArrayList<String> strings = roleJudgment(loginmanId);
        for (String string : strings) {
            String date = time.format(new Date());
            //用户
            if (string.equals("平台客户") && userFlag.equals("0")) {
                //用户的各订单数量
                List<CustomerRepair> customerRepairList = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>().eq("customer_id", loginmanId));
                customerRepairList.forEach(a -> customerRepairsList.add(a));
                //未读订单数量
                for (CustomerRepair customerRepair : customerRepairList) {
                    SysNotice read_no = sysNoticeMapper.selectOne(new QueryWrapper<SysNotice>().eq("read_no", "0")
                            .eq("customer_key", customerRepair.getCustomerKey()));
                    if (read_no != null) announcement++;
                }
                //用户的所有未读订单
                List<CustomerRepair> user = customerRepairMapper.selectListByloginmanId(loginmanId);
                if (user.size() != 0) user.forEach(a -> customerRepairsList.add(a));

            }
            //财务的的未读订单数量
            if (string.equals("分公司财务") && userFlag.equals("1")) {
                //财务各订单数量
                List<CustomerRepair> customerRepairList = customerRepairMapper.selectListFinance(loginmanId, null, String.valueOf(aLong));
                customerRepairList.forEach(a -> customerRepairsList.add(a));
                //财务未读订单数量
                List<CustomerRepair> customerRepairListcount = customerRepairMapper.selectListFinance(loginmanId, "0", String.valueOf(aLong));
                announcement = announcement + customerRepairListcount.size();
            }
            //审核人员的
            if (string.equals("分公司运维部门负责人")&& userFlag.equals("1")) {
                //审核人员所有的订单
                List<CustomerRepair> customerRepairs = customerRepairMapper.selectListByAudit(loginmanId, null, String.valueOf(aLong));//type未读状态
                if (customerRepairs.size() != 0) customerRepairs.forEach(a -> customerRepairsList.add(a));
                //未读消息数量
                List<CustomerRepair> customerRepairscount = customerRepairMapper.selectListByAudit(loginmanId, "0", String.valueOf(aLong));//type未读状态
                announcement = announcement + customerRepairscount.size();
            }
            //分公司施工人员
            if (string.equals("分公司施工人员")&& userFlag.equals("1")) {
                //根据施工人员查看所有订单--无状态查看所有订单
                List<CustomerRepair> customerRepairs = customerRepairMapper.selectListByWorker(loginmanId, null, String.valueOf(aLong));
                customerRepairs.forEach(a -> customerRepairsList.add(a));
                //根据师傅的公司id和师傅id查看未读订单
                List<CustomerRepair> customerRepairscount = customerRepairMapper.selectListByWorker(loginmanId, "0", String.valueOf(aLong));
                announcement = announcement + customerRepairscount.size();
            }
        }
        map.put("announcement", announcement);//公告未读信息
        HashMap<String, Integer> stringIntegerHashMap = getStringIntegerHashMap(customerRepairsList, map);
        return R.ok(stringIntegerHashMap);
    }

    @Override
    public Boolean JudgeTheRole(JSONObject jsonObject) {
        String loginmanId = jsonObject.getString("loginmanId");
        //根据登录人id去分辨是用户还是
        /*String userFlag = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id", loginmanId).select("user_flag")).getUserFlag();
        //判断是不是审核人员
        ArrayList<String> strings = roleJudgment(loginmanId);
        for (String string : strings) {
            if (string.equals("分公司运维部门负责人")&& userFlag.equals("1")) {
                return true;
            }
        }
        return false;*/
        List<SysUser> users = sysUserMapper.selectWorkerByDept("100", "audit_order");
        if (users.size() > 0) {
            for (SysUser user : users) {
                if (Objects.equals(user.getUserId(), new Long(loginmanId))) {
                    return true;
                }
            }
        }
        return false;
    }

    public ArrayList<String> roleJudgment(String userId) {
        ArrayList<String> strings = new ArrayList<>();
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", userId).select("role_id"));
        for (SysUserRole sysUserRole : sysUserRoles) {
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614512006252556289"))) strings.add("平台客户");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614510342669955074"))) strings.add("分公司经理");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614510568130572289"))) strings.add("分公司运维部门负责人");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614510938101739521"))) strings.add("分公司接待部门负责人");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1628948985328189441"))) strings.add("分公司财务");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1614511218876837889"))) strings.add("分公司施工人员");
            if (sysUserRole.getRoleId().equals(Long.parseLong("1623626502560641026"))) strings.add("分公司电站人员");
        }
        return strings;
    }
//    /**
//     * @Description 接口描述 : 微信三方登录
//     * 流程如下 ;
//     *   1 . 接收小程序发送的code
//     *   2 . 开发者服务器 登录凭证校验接口 appi + appsecret + code
//     *   3 . 接收微信接口服务 获取返回的参数
//     *   4 . 校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//     *   5 . 根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
//     * @Params  * @param null
//     * @Return
//     * @Author xiaw
//     * @Date 2023/2/16 17:31
//     */
//    @Override
//    public ResultMsg weChat(String code) {
//        String jsonSter
//                = HttpUtil.getCharset(WxConstants.GET_ACK_URL
//                .replace("APPID", WxConstants.APPID)//替换指定的字符
//                .replace("SECRET", WxConstants.SECRET)
//                .replace("CODE", code));//这个才是要发送请求的路径
//        return null;
//    }

    /**
     * @Description 接口描述 :
     * @Params * @param null
     * @Return 循环放进
     * @Author xiaw
     * @Date 2023/1/31 16:09
     */
    private void addcustome(LinkedHashSet<CustomerRepair> customerRepairsList, Long aLong, List<Ticket> tickets) {
        if (tickets.size() != 0) {
            for (Ticket ticket : tickets) {
                List<CustomerRepair> master = customerRepairMapper.selectList(new QueryWrapper<CustomerRepair>().eq("customer_key", ticket.getTicketRepair()).eq("company_id", aLong));
                master.forEach(a -> customerRepairsList.add(a));
            }
        }
    }

    /**
     * @Description 接口描述 :
     * @Params * @param null
     * @Return 统计订单  announcement
     * @Author xiaw
     * @Date 2023/1/31 15:50
     */
    @NotNull
    private HashMap<String, Integer> getStringIntegerHashMap(LinkedHashSet<CustomerRepair> list, HashMap<String, Integer> map) {
        Integer pendingOrder = 0;
        Integer receivedOrder = 0;
        Integer toBeReviewed = 0;
        Integer toBeInvestigated = 0;
        Integer toBeQuoted = 0;
        Integer toBeConstructed = 0;
        Integer toBeAccepted = 0;
        Integer obligation = 0;
        Integer financialRecognition = 0;
        Integer accountPaid = 0;
        Integer offTheStocks = 0;
        Integer closed = 0;
        Integer contractToBeSigned = 0;


        for (CustomerRepair customerRepair : list) {
            //订单状态
            String customerFlag = customerRepair.getCustomerFlag();
            //待接单和工单池订单
            if (customerFlag.equals("0") || customerFlag.equals("99")) pendingOrder++;//待接单数量
            if (customerFlag.equals("21")) receivedOrder++;//已接单
            if (customerFlag.equals("8")) toBeReviewed++;//待审核
            if (customerFlag.equals("9")) toBeInvestigated++;//待勘察
            if (customerFlag.equals("1")) toBeQuoted++;//待报价
            if (customerFlag.equals("3")) toBeConstructed++;//待施工
            if (customerFlag.equals("4")) toBeAccepted++;//待验收
            if (customerFlag.equals("5")) obligation++;//待付款
            if (customerFlag.equals("11")) financialRecognition++;//财务确认
            if (customerFlag.equals("10")) accountPaid++;//已付款
            if (customerFlag.equals("7")) offTheStocks++;//已完成
            if (customerFlag.equals("77")) closed++;//已关闭
            if (customerFlag.equals("98")) contractToBeSigned++;//待签单
        }

        map.put("pendingOrder", pendingOrder);//待接单数量
        map.put("receivedOrder", receivedOrder);//已接单
        map.put("toBeReviewed", toBeReviewed);//待审核
        map.put("toBeInvestigated", toBeInvestigated);//待审核
        map.put("toBeQuoted", toBeQuoted);//待报价
        map.put("toBeConstructed", toBeConstructed);//待施工
        map.put("toBeAccepted", toBeAccepted);//待验收
        map.put("obligation", obligation);//待付款
        map.put("financialRecognition", financialRecognition);//财务确认
        map.put("accountPaid", accountPaid);//已付款
        map.put("offTheStocks", offTheStocks);//已完成
        map.put("closed", closed);//已关闭
        map.put("contractToBeSigned", contractToBeSigned);//待签单
        return map;
    }

    /**
     * 工单回退
     */
    public void orderBack(JSONObject jsonObject) {
        String orderId = jsonObject.getString("orderId");
        String userId = jsonObject.getString("userId");
        if (StringUtils.isBlank(orderId)) {
            throw new ServiceException("工单编号不能为空");
        }
        CustomerRepair order = customerRepairMapper.selectById(orderId);
        if (order == null) {
            throw new ServiceException("工单不存在");
        }
        if ("4".equals(order.getCustomerFlag())) {
            // 客户验收->施工
            MaterialInfo materialInfo = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>()
                    .eq("material_repari", orderId)
                    .orderByDesc("create_time")
                    .last("LIMIT 1"));
            if (materialInfo != null) {
                materialBeforeMapper.delete(new QueryWrapper<MaterialBefore>()
                        .eq("material_repari", orderId).eq("ids", materialInfo.getMaterialKey()));
                materialAfterMapper.delete(new QueryWrapper<MaterialAfter>()
                        .eq("material_repari", orderId).eq("ids", materialInfo.getMaterialKey()));
                materialInfoMapper.deleteById(materialInfo.getMaterialKey());
            }
            order.setCustomerFlag("3");
            order.setUpdateTime(new Date());
            order.setUpdateBy(userId);
            order.setBuildTime(null);
            order.setCompleteTime(null);
            MaterialInfo materialInfo2 = materialInfoMapper.selectOne(new QueryWrapper<MaterialInfo>()
                    .eq("material_repari", orderId)
                    .orderByDesc("create_time")
                    .last("LIMIT 1"));
            if (materialInfo2 != null) {
                order.setBuildTime(materialInfo2.getCreateTime());
                order.setCompleteTime(materialInfo2.getCreateTime());
            }
        }
    }
}
